<template>
  <div class="ky-container" ref="content">
    <div @click="dlgClose" style="min-height: calc(100vh - 150px);">
      <el-card shadow="hover" class="ky-card ky-card-xs ky-card-hdbg">
        <el-form
          ref="form"
          :model="formData"
          :rules="rules"
          :inline="true"
          class="apply-card ky-form-inline ky-form-inline-sm"
          label-width="80px">
          <el-form-item label="医院名称" prop="hospitalCode">
            <el-select
              size="small"
              class="param-type_input"
              filterable
              v-model="formData.hospitalCode"
              placeholder="请选择"
              @change="handleChange($event, 'hospital')">
              <el-option
                v-for="(item,index) in mx_hospitalList"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="患者姓名">
            <el-input size="small" v-model="formData.patientName" @keyup.enter.native="toSearch" clearable placeholder="请输入" style="width: 160px;"></el-input>
          </el-form-item>
          <!-- 卡号等 searchValue searchCommonValue-->
          <el-form-item class="select-pd5">
            <el-input
              id="formQueryTextIptInSourceEnquiry"
              ref="formQueryTextIptInSourceEnquiry"
              size="small"
              style="text-align:left"
              v-model="searchCommonValue"
              clearable
              placeholder="请输入"
              @input="changeInput"
              @clear="searchValueReset"
              @keyup.enter.native="toSearch"
            >
              <el-select v-model="searchValue" slot="prepend" style="width:116px" placeholder="请选择" @change="searchValueChange">
                <el-option
                  v-for="item in searchOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <!-- 福鼎添加要求 -->
          <el-form-item class="select-pd5 select-time">
            <el-select class="borderChangeSelect" v-model="dateValue" style="width:102px;border-top-right-radius: 0px !important;border-bottom-right-radius: 0px !important;" placeholder="请选择">
              <el-option
                v-for="item in dateOptions"
                :key="item.label"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
            <!-- <el-input size="small" style="text-align:left" v-model="dateCommonValue" clearable placeholder="请输入"></el-input> -->
            <el-date-picker
              class="changeBorder"
              v-model="timeRange"
              @change="timeRangeChange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              :clearable="false"
              style="width: 295px;"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="检查部门" v-if="!isFilterMerge">
            <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.scheduledDep" multiple placeholder="请选择" clearable :collapse-tags="!isGetHisDeps" @change="handleChange('scheduledDep')">
              <el-option
                v-for="(item,index) in scheduledDepOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请科室" v-if="!isFilterMerge && isShowApplyDepart">
            <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.sqdep" placeholder="请选择" :disabled="isDisabled" clearable collapse-tags @change="handleChange('applyDepartment')">
              <el-option
                v-for="(item,index) in departmentOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="病区" v-if="!isFilterMerge && (isShowWardNo || isShowWardNo2)">
            <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.wardNo" :disabled="wardNoDisabled" @change="handleChange('wardNo')" placeholder="请选择" clearable>
              <el-option
                v-for="(item,index) in wardNoOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="患者类型" v-if="!isFilterMerge">
            <el-select multiple size="small" style="width: 160px;" class="param-type_input" v-model="formData.PatientType" placeholder="请选择" clearable @change="handleChange('PatientType')">
              <el-option
                v-for="(item,index) in patientTypeOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预约来源" v-if="!isFilterMerge">
            <el-select multiple size="small" style="width: 160px;" class="param-type_input" v-model="formData.appointmentType" placeholder="请选择" clearable @change="handleChange('PatientType')">
              <el-option
                v-for="(item,index) in appointmentTypeOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-for="(item, index) in leftOptionsShort" :key="index" v-if="isFilterMerge && !isExtend">
            <!-- 左边 -->
            <el-select
              size="small"
              style="width:110px"
              v-model="selectedLeft[index]"
              @change="handleLeftChange(index)"
              ref="leftSelect">
              <el-option
                v-for="option in leftOptions"
                :disabled="option.disabled"
                :key="option.field"
                :label="option.label"
                :value="option.field"
              />
            </el-select>
            <!-- 右边短 -->
            <el-select
              v-if="selectedLeft[index] != 'medcine' && selectedLeft[index] != 'bedside' && selectedLeft[index] != 'chargeStatus' && selectedLeft[index] != 'numberPrintStatus'"
              :style="{ width: rightGroupWidth[index] + 'px' }"
              v-model="selectedRight[index]"
              @change="handleRightChange(index, selectedLeft[index])"
              :placeholder="rightPlaceholders[index]"
              key="多选"
              :filterable="selectedLeft[index] === 'callRoom'"
              clearable
              collapse-tags
              multiple
            >
              <el-option
                v-for="option in getRightOptions(selectedLeft[index])"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
            <el-select
              v-else
              :style="{ width: rightGroupWidth[index] + 'px' }"
              v-model="selectedRight[index]"
              @change="handleRightChange(index, selectedLeft[index])"
              :placeholder="rightPlaceholders[index]"
              key="单选"
              filterable
              clearable
              collapse-tags>
              <el-option
                v-for="option in getRightOptions(selectedLeft[index])"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
          </el-form-item>
          <span v-show="isExtend == 1">
            <el-form-item label="影像区域" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.depArea" multiple placeholder="请选择" clearable collapse-tags @change="handleChange('depArea')">
                <el-option
                  v-for="(item,index) in depAreaOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查设备" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.scheduledModality" multiple placeholder="请选择" clearable collapse-tags @change="handleChange('scheduledModality')">
                <el-option
                  v-for="(item,index) in scheduledModalityOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查分组" v-if="!isFilterMerge">
              <el-select
                size="small"
                style="width: 160px;"
                multiple
                class="param-type_input"
                v-model="formData.checkGroup"
                @change="handleChange('checkGroup')"
                filterable
                placeholder="请选择"
                clearable
                collapse-tags>
                <el-option
                  v-for="(item,index) in checkGroupOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查机房" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.callRoom" @change="handleChange('callRoom')" multiple filterable placeholder="请选择" clearable collapse-tags>
                <el-option
                  v-for="(item,index) in callRoomOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预约机房" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.scheduledRoom" @change="handleChange('scheduledRoom')" multiple filterable placeholder="请选择" clearable collapse-tags>
                <el-option
                  v-for="(item,index) in callRoomOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查部位" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" v-model="formData.dengjipart" multiple placeholder="请选择" filterable clearable collapse-tags @change="handleChange('dengjipart')">
                <el-option
                  v-for="(item,index) in dengjipartOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查项目" v-if="!isFilterMerge">
              <virtualselect
                :data="checkposOptions"
                v-model="formData.checkpos"
                placeholder="请选择"
                clearable
                multiple
                @change="handleChange('checkpos')"
              ></virtualselect>
            </el-form-item>
            <el-form-item label="检查班次" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.medcine" @change="handleChange('medcine')" filterable placeholder="请选择" clearable collapse-tags>
                <el-option
                  v-for="(item,index) in medcineOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检查状态" v-if="!isFilterMerge">
              <!-- multiple -->
              <el-select size="small" style="width: 160px;" multiple class="param-type_input" v-model="formData.checkStatus" @change="handleChange('checkStatus')" placeholder="请选择" clearable>
                <el-option
                  v-for="(item,index) in checkStatusOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="打印状态" v-if="!isFilterMerge">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.numberPrintStatus" @change="handleChange('numberPrintStatus')" placeholder="请选择" clearable>
                <el-option
                  v-for="(item,index) in printType"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优先级别" v-if="!isFilterMerge">
              <el-select
                size="small"
                multiple
                style="width: 160px;"
                class="param-type_input"
                v-model="formData.grade"
                @change="handleChange('grade')"
                filterable
                clearable>
                <el-option
                  v-for="(item, index) in gradeOptions"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运送方式" v-if="!isFilterMerge && isInsertTransportType">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.transportType" @change="handleChange('transportType')" filterable clearable>
                <el-option
                  v-for="(item, index) in transportTypeOptions"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="转运工具" v-if="!isFilterMerge && isInsertTransportType">
              <el-select size="small" style="width: 160px;" class="param-type_input" v-model="formData.transportTools" @change="handleChange('transportTools')" filterable clearable>
                <el-option
                  v-for="(item, index) in transportToolsOptions"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收费状态" prop="chargeStatus" v-if="!isFilterMerge">
              <el-select style="width: 160px;" v-model="formData.chargeStatus" @change="handleChange('chargeStatus')" placeholder="请选择" clearable>
                <el-option
                  v-for="item in chargeStatusOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="床旁标志" v-if="!isFilterMerge && isMpiOrPid">
              <el-select size="small" style="width:160px" class="param-type_input" v-model="formData.bedside" @change="handleChange('bedside')" placeholder="请选择" clearable>
                <el-option
                  v-for="(item,index) in bedsideOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="HIS类型" v-if="!isFilterMerge && isShowHisType">
              <el-select size="small" style="width:160px" class="param-type_input" v-model="formData.hisType" @change="handleChange('hisType')" placeholder="请选择" clearable>
                <el-option
                  v-for="(item,index) in hisTypeOptions"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="isFilterMerge"
              v-for="(item, index) in leftOptions"
              :key="index"
              :style="index === 0 ? 'margin-right: 30px;margin-left: 6px;': 'margin-right: 30px;'">
              <!-- 左边 -->
              <el-select
                size="small"
                style="width:110px"
                v-model="selectedLeft[index]"
                @change="handleLeftChange(index)"
                ref="leftSelect">
                <el-option
                  v-for="option in leftOptions"
                  :disabled="option.disabled"
                  :key="option.field"
                  :label="option.label"
                  :value="option.field"
                />
              </el-select>
              <!-- 右边 -->
              <el-select
                :style="{ width: rightGroupWidth[index] + 'px' }"
                v-if="selectedLeft[index] != 'medcine' && selectedLeft[index] != 'bedside' && selectedLeft[index] != 'chargeStatus' && selectedLeft[index] != 'numberPrintStatus'"
                v-model="selectedRight[index]"
                @change="handleRightChange(index, selectedLeft[index])"
                :placeholder="rightPlaceholders[index]"
                key="多选"
                :filterable="selectedLeft[index] === 'callRoom'"
                clearable
                collapse-tags
                multiple
              >
                <el-option
                  v-for="option in getRightOptions(selectedLeft[index])"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
              <el-select
                v-else
                :style="{ width: rightGroupWidth[index] + 'px' }"
                v-model="selectedRight[index]"
                @change="handleRightChange(index, selectedLeft[index])"
                :placeholder="rightPlaceholders[index]"
                key="单选"
                filterable
                clearable
                collapse-tags>
                <el-option
                  v-for="option in getRightOptions(selectedLeft[index])"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </el-form-item>
          </span>
          <el-form-item label="">
            <el-checkbox v-model="formData.DeleteStatus">排除已删除</el-checkbox>
          </el-form-item>
          <el-form-item label="">
            <el-tooltip class="item" effect="dark" content="患者姓名查询时间段超过一年以上的请勾选精准查询" placement="top-start">
              <el-checkbox v-model="isAccurate">精准查询</el-checkbox>
            </el-tooltip>
          </el-form-item>
          <el-form-item>
            <div class="flex flex-row align-center">
              <el-button :type="isStyleUpdate ? 'warning' : 'primary'" class="m-l-0" size="small" icon="el-icon-search" :loading="loading" @click="search">查询</el-button>
              <WSCardReader class="mar-l-5" ref="WSCardReader" btn-size="mini" @getWSCardReaderMsg="getWSCardReaderMsg"/>
              <el-button class="mar-l-5" size="small" icon="el-icon-refresh-right" @click="resetParam" plain>重置</el-button>
              <el-button class="m-l-0" size="small" :icon="isExtend == 1 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" @click="extendBtn" plain>{{isExtend == 1 ? '收缩' : '展开'}}</el-button>
              <el-tooltip class="item" effect="dark" content="设置功能可对表单的字段显示做开关与排序" placement="top-start">
                <el-button class="m-l-0" size="small" icon="el-icon-setting" @click="openSettings" plain>设置</el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="'记住选择'按钮的使用方法:改变筛选条件后,再次点击'记住选择'后才会真正记住筛选条件" placement="top-start">
                <el-button class="m-l-0" size="small" v-if="isShowRememberSelectBtn" @click="rememberSelectBtn" plain>{{'记住选择'}}</el-button>
              </el-tooltip>
              <el-button class="m-l-0" size="small" @click="signIn" plain v-permission="'YJYY10008060'">内镜签到</el-button>
              <el-button v-if="exportToExcel" size="small" @click="exportToExcelBtn">导出Excel</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="hover" class="ky-card ky-card-hdbg ky-mt10">
        <el-table
          ref="table"
          v-loading="loading"
          @sort-change="sortBys"
          :data="tableData"
          style="width: 100%"
          border
          class="ky-table yiji-table"
          :stripe="true"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange">
          <!-- :default-sort="{prop: 'checkStatus', order: 'descending'}" -->
          <el-table-column
            type="selection"
            :selectable="selectableEvent"
            :show-overflow-tooltip="false"
            width="40">
            <!-- v-bind="tableFixed" -->
          </el-table-column>
          <!-- v-bind="tableFixed" -->
          <!-- :width="isPrintReport ? '450' : '300'" -->
          <!-- (isMpiOrPid && !isPrintReport) ? '200':'380' -->
          <el-table-column align="center" label="操作" :width="tableOperateWidth" @width-change="handleColumnWidthChange">
            <template slot-scope="scope">
              <div class="flex flex-row justify-center">
                <!-- isStyleUpdate? -->
                <el-button :title="scope.row.checkStatus === '已审核' ? '已审核不能改约和取消' : ''" type="primary" size="mini" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" @click.stop="handleEdit(scope.$index, scope.row)" :disabled="scope.row.checkStatus === '已删除' || (scope.row.checkStatus === '已审核' && isCheckedNoCancel)">
                  改约
                </el-button>
                <el-button :title="scope.row.checkStatus === '已审核' ? '已审核不能改约和取消' : ''" :type="isStyleUpdate ? '' : 'success'" size="mini" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" @click.stop="handleCancel(scope.$index, scope.row)" :disabled="scope.row.checkStatus === '已删除' || (scope.row.checkStatus === '已审核' && isCheckedNoCancel)">
                  取消
                </el-button>
                <el-button type="warning" size="mini" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" v-if="!isMpiOrPid" @click.stop="handlePrint(scope.$index, scope.row)" :disabled="scope.row.checkStatus === '已删除' || scope.row.chargeStatus === '未收费'">
                  {{isPrintReport ? '打印号码单' : '打印'}}
                </el-button>
                <el-button type="printReport" size="mini" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" v-if="!isMpiOrPid && isPrintReport" @click.stop="handlePrintReport(scope.$index, scope.row)" :disabled="scope.row.checkStatus === '已删除' || canPrintStatus.indexOf(scope.row.checkStatus) == -1">
                  打印报告单
                </el-button>
                <el-dropdown style="margin-left: 6px;">
                  <el-button size="mini" type="plain" style="width: 70px;">
                    更多<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="handlePrint(scope.$index, scope.row)">
                      <span><i class="el-icon-printer"></i>打印号码单</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handlePrintReport(scope.$index, scope.row)" v-show="isPrintReport" :disabled="canPrintStatus.indexOf(scope.row.checkStatus) == -1">
                      <span><i class="el-icon-printer"></i>打印报告单</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleApply(scope.$index, scope.row)">
                      <span><i class="el-icon-user"></i>详情</span>
                    </el-dropdown-item>
                    <!-- v-permission="'YJYY20000001'" -->
                    <el-dropdown-item v-if="scope.row.checkStatus !== '已删除' && isAddAuthInEdit && $hasPermission(['YJYY20000001'])" @click.native="handleEditPat(scope.$index, scope.row)">
                      <span><i class="el-icon-user"></i>编辑</span>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="!isAddAuthInEdit" @click.native="handleEditPat(scope.$index, scope.row)">
                      <span><i class="el-icon-user"></i>编辑</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleLog(scope.$index, scope.row)">
                      <span><i class="el-icon-tickets"></i>日志</span>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.checkStatus === '已删除'" @click.native="handleTFPrint(scope.$index, scope.row)">
                      <span><i class="el-icon-printer"></i>退费打印</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleApplySave(scope.$index, scope.row)" v-if="applyCheckFileSHow">
                      <span><i class="el-icon-tickets"></i>申请单保存</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleApplyPreview(scope.$index, scope.row)" v-if="applyCheckFileSHow">
                      <span><i class="el-icon-tickets"></i>申请单预览</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleMessageLog(scope.$index, scope.row)" v-permission="'YJYY10008042'">
                      <span><i class="el-icon-chat-dot-square"></i>短信列表</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleCheck(scope.$index, scope.row)" v-permission="'YJYY10008052'">
                      <span><i class="el-icon-edit-outline"></i>绿检登记</span>
                    </el-dropdown-item>
                    <el-dropdown-item @click.native="handleSupplementary(scope.$index, scope.row)" v-permission="'YJYY10008063'">
                      <span><i class="el-icon-edit-outline"></i>补费更新</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
          <!-- v-bind="tableFixed" -->
          <el-table-column v-for="(item, index) in tableColumn" v-if="!!(~~item.x)" :key="index" :prop="item.p" :label="item.n" :sortable="judgeTrueOrFalse(item.p)" :show-overflow-tooltip="!!item.t" :min-width="(item.w || 90) + 'px'">
            <template slot-scope="scope">
              <span v-if="item.p == 'idCard'" style="mso-number-format: '\@';">
                {{scope.row.idCard}}
              </span>
              <div class="flex flex-row justify-between align-center" style="width: 100%;" v-else-if="item.p == 'patientNameSex'">
                <span class="ellipsis-text-line1">{{scope.row.patientName}}</span>
                <img class="sexIcon" src="../../../assets/images/man.png" alt="男" title="男" v-if="scope.row.patientSex === '男'">
                <img class="sexIcon" src="../../../assets/images/woman.png" alt="女" title="女" v-if="scope.row.patientSex === '女'">
              </div>
              <span v-else-if="item.p == 'birthday'">
                {{getBirthDay(scope.row.patientBirthDate)}}
              </span>
              <span v-else-if="item.p == 'checkExamPart'">
                （{{scope.row.scheduledDep}}){{scope.row.checkpos}}
              </span>
              <span v-else-if="item.p == 'beginEndTime'">
                {{scope.row.beginTime ? scope.row.beginTime.substring(0, 5) : ''}} ~ {{scope.row.endTime ? scope.row.endTime.substring(0, 5) : ''}}
              </span>
              <div class="flex flex-row justify-between align-center" style="width: 100%;" v-else-if="item.p == 'callId'">
                <el-tag size="small" type="danger">{{scope.row.callType ? scope.row.callType + scope.row.callId : scope.row.callId}}</el-tag>
              </div>
              <div class="flex flex-row justify-between align-center" style="width: 100%;" v-else-if="item.p == 'confirmationNum'">
                <!-- <el-tag v-if="scope.row.callType" size="small" type="danger"></el-tag> -->
                <el-tag size="small" type="danger" v-if="scope.row.confirmationNum">{{scope.row.confirmationNum}}</el-tag>
                <!-- <span class="red" v-if="scope.row.confirmationNum">{{scope.row.confirmationNum}}</span> -->
              </div>
              <span v-else-if="item.p == 'scheduledDttm'">
                {{frtTime(scope.row.scheduledDttm)}}
              </span>
              <span v-else-if="item.p == 'triggerDttm'">
                {{frtTime(scope.row.triggerDttm)}}
              </span>
              <span v-else-if="item.p == 'checkDttm'">
                {{paramCheckDttm(scope.row.checkDttm)}}
              </span>
              <div v-else-if="item.p == 'checkStatus'">
                <el-link size="mini" :type="frStatus(scope.row.checkStatus)" v-if="scope.row.checkStatus == 200">未报告</el-link>
                <el-link size="mini" :type="frStatus(scope.row.checkStatus)">{{scope.row.checkStatus}}</el-link>
              </div>
              <div v-else-if="item.p == 'numberPrintStatus'">
                <el-tag size="mini" hit :type="prStatus(scope.row.numberPrintStatus)">{{prStatus(scope.row.numberPrintStatus) === 'warning' ? '未打印': scope.row.numberPrintStatus}}</el-tag>
              </div>
              <span v-else-if="item.p == 'testPatientId'">
                {{(applyInfoHospital === 'wzszxyy' || formData.hospitalCode === '47052555733030211A1001') && (scope.row.patientType === '门诊' || scope.row.patientType === '住院') ? '' : scope.row.testPatientId}}
              </span>
              <div v-else-if="item.p == 'jzpb'">
                {{emergencyOptionsMapFromDB[(scope.row.jzpb||'')]}}
              </div>
              <div class="flex flex-row justify-between align-center" style="width: 100%;" v-else-if="item.p == 'patientType'">
                <span class="ellipsis-text-line1">{{scope.row.patientType}}</span>
                <span class="mergeIcon1" alt="主" title="主申请单" v-if="scope.row.mergeAccessNo && scope.row.mergeAccessNo == scope.row.ticketId">主</span>
                <span class="mergeIcon2" @dblclick="copyText" :data-text="scope.row.mergeAccessNo" alt="从" :title="'申请单'+ scope.row.mergeAccessNo +'的子申请单'" v-if="scope.row.mergeAccessNo && scope.row.mergeAccessNo !== scope.row.ticketId">从</span>
              </div>
              <div v-else>
                <span>{{scope.row[item.p]}}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="display:flex;justify-content: space-between; align-items:center;">
          <div>
            <!-- 有急诊权限代表前台的护士和管理员，要显示批量打印，为合并打印 -->
            <el-tooltip class="item" effect="dark" content="同患者同设备同班次指定项目合并打印。" placement="top-start" v-if="isMpiOrPid">
              <el-button :type="isStyleUpdate ? 'warning' : 'warning'" :disabled="multipleSelection.length === 0" size="small" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" style=" height: 32px;" @click="batchPrint" v-show="$hasPermission(['YJYY10007001'])">{{isPrintReport ? '批量打印号码单' : '批量打印'}}</el-button>
            </el-tooltip>
            <el-button :type="isStyleUpdate ? 'primary' : 'warning'" :disabled="multipleSelection.length === 0" size="small" :class="isStyleUpdate ? 'styleUpdate' : ''" style=" height: 32px;" @click="batchRebook">批量改约</el-button>
            <el-button :type="isStyleUpdate ? '' : 'warning'" :disabled="multipleSelection.length === 0" size="small" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" style=" height: 32px;" @click="batchPrint" v-if="!isMpiOrPid">批量打印</el-button>
            <!-- <el-button v-show="isPrintReport" type="primary" :disabled="multipleSelection.length === 0" size="small" style=" height: 32px;" @click="batchPrintReport">{{isPrintReport ? '批量打印报告单' : '批量打印'}}</el-button> -->
            <!-- 没有有急诊权限代表诊间医生，要显示床旁批量打印 -->
            <el-tooltip class="item" effect="dark" content="不合并同患者的号码单" placement="top-start" v-if="isMpiOrPid">
              <el-button :type="isStyleUpdate ? '' : 'primary'" :disabled="multipleSelection.length === 0" size="small" :class="isStyleUpdate ? 'table-operation-btn styleUpdate' : 'table-operation-btn'" style=" height: 32px;" @click="bedSidePrint" v-show="!$hasPermission(['YJYY10007001'])">床旁批量打印</el-button>
            </el-tooltip>
            <!-- <el-button :class="multipleSelection.length === 0 ? 'no-message':'choose-message'" :disabled="multipleSelection.length === 0" size="small" v-permission="'YJYY10008042'" @click="batchMessage">批量发送短信</el-button>
            <el-button :class="multipleSelection.length === 0 ? 'no-sign':'choose-sign'" :disabled="multipleSelection.length === 0" v-permission="'YJYY10008043'" size="small" @click="batchSign">批量签到</el-button>
            <el-button :class="multipleSelection.length === 0 ? 'no-call':'choose-call'" :disabled="multipleSelection.length === 0" v-permission="'YJYY10008044'" size="small" @click="batchCall">批量报告单呼叫</el-button> -->
            <el-button :class="{'no-message': multipleSelection.length === 0, 'choose-message': multipleSelection.length !== 0, 'styleUpdate': isStyleUpdate}" :disabled="multipleSelection.length === 0" size="small" v-permission="'YJYY10008042'" @click="batchMessage">批量发送短信</el-button>
            <el-button :class="{'no-sign': multipleSelection.length === 0, 'choose-sign': multipleSelection.length !== 0, 'styleUpdate': isStyleUpdate}" :disabled="multipleSelection.length === 0" v-permission="'YJYY10008043'" size="small" @click="batchSign">批量签到</el-button>
            <el-button :class="{'no-call': multipleSelection.length === 0, 'choose-call': multipleSelection.length !== 0, 'styleUpdate': isStyleUpdate}" :disabled="multipleSelection.length === 0" v-permission="'YJYY10008044'" size="small" @click="batchCall">批量报告单呼叫</el-button>
            <el-tooltip
              class="item"
              effect="dark"
              :content="delTips[showDelBtn]"
              placement="top-start"
              v-if="showDelBtn"
            >
              <span style="margin-left: 5px;">
                <el-button :type="isStyleUpdate ? '' : 'info'" :class="isStyleUpdate ? 'styleUpdate' : ''" :disabled="!!showDelBtn" size="small" style=" height: 32px;" @click="batchCancel">
                  批量取消
                </el-button>
              </span>
            </el-tooltip>
            <el-button :type="isStyleUpdate ? '' : 'info'" :class="isStyleUpdate ? 'styleUpdate' : ''" v-else size="small" style=" height: 32px;" @click="batchCancel">批量取消</el-button>
            <!-- 没有有急诊权限代表诊间医生，要显示床旁批量打印 -->
            <el-tooltip class="item" effect="dark" content="同患者同设备同班次指定项目合并打印。" placement="top-start" v-if="isMpiOrPid">
              <el-button :type="isStyleUpdate ? '' : 'warning'" :disabled="multipleSelection.length === 0" size="small" :class="isStyleUpdate ? 'styleUpdate' : ''" style=" height: 32px;margin-left: 5px;" @click="batchPrint" v-show="!$hasPermission(['YJYY10007001'])">{{isPrintReport ? '批量打印号码单' : '批量打印'}}</el-button>
            </el-tooltip>
            <!-- 有急诊权限代表前台的护士和管理员，要显示批量打印，为合并打印 -->
            <el-tooltip class="item" effect="dark" content="不合并同患者的号码单" placement="top-start" v-if="isMpiOrPid">
              <el-button :type="isStyleUpdate ? '' : 'primary'" :disabled="multipleSelection.length === 0" size="small" :class="isStyleUpdate ? 'styleUpdate' : ''" style=" height: 32px;margin-left: 5px;" @click="bedSidePrint" v-show="$hasPermission(['YJYY10007001'])">床旁批量打印</el-button>
            </el-tooltip>
          </div>
          <paginationCont
            :total="totalCount"
            :page.sync="currentPage"
            :limit.sync="pageSize"
            @pagination="changePagenation"
          />
        </div>
      </el-card>
    </div>
    <!-- 拍照 -->
    <cameraPhoto ref="cameraDlg" :row="appoDetail" v-if="isOpenCamera"></cameraPhoto>
    <!-- 申请单信息 -->
    <InfoDialog
      ref="infoDialog"
      v-if="isShowInfoDialog"
      :is-show-result="isShowResult"
      :appo-info="appoDetail"
      :dialog-visible.sync="dialogVisibleDetail">
    </InfoDialog>
    <!--纸质申请单图片预览-->
    <!-- :image-list="applyImageList" -->
    <applyImageDialog
      ref="applyImageDialog"
      :row="appoDetail"
      title="申请单预览"
      :dialog-visible.sync="applyImageDialogVisible">
    </applyImageDialog>
    <!--修改患者信息-->
    <PatBasicInfo ref="patBasicInfo" :hospital-code="formData.hospitalCode" @close="close('PatBasicInfo')" @changePatBasicInfo="fetchData" v-if="patBasicInfoVisible"></PatBasicInfo>
    <SendMessage ref="sendMessage" @changeSendMessage="fetchData"></SendMessage>
    <!-- 改约 -->
    <EditAppoDialog
      ref="EditAppoDialog"
      @changeAppo="fetchData"
      @closeDialog="closeDialog"
      :hospital-code="formData.hospitalCode"
      :dialog-visible-edit-appo.sync="dialogVisibleEditAppo"
      :is-edit-info.sync="isEditInfo"
      :hospital-code-form="formData.hospitalCode"
      :hospital-name-form="hospitalName"
      :from-check-department.sync="fromCheckDepartment"
      :title-change.sync="titleChange"
    >
    </EditAppoDialog>
    <!-- 日志 -->
    <LogDialog
      v-if="isShowLogDialog"
      ref="LogDialog"
      :id="logId"
      :hospital-code="formData.hospitalCode"
      :dialog-visible.sync="dialogVisibleLog">
    </LogDialog>
    <MessageDialog
      ref="MessageDialog"
      :id="logId"
      :hospital-code="formData.hospitalCode"
      :dialog-visible.sync="dialogMessageLog">
    </MessageDialog>
    <!-- 签到界面 -->
    <SignUpDialog v-if="isShowSignUpDialog" ref="signIn" @getSignInfo="getSignInfo" :hospital-code="hospitalCode" :appoint-type="appoint_type"/>
    <!-- 打印 -->
    <PrintAppo :loading-print.sync="loading" ref="PrintAppo"/>
    <SetIndexDialog ref="setIndexDialog" v-if="isShowSetIndexDialog"/>
    <HisRecordDialog ref="HisRecardDialog" v-if="isShowHisDialog" @emitRecordDialog="fetchData"></HisRecordDialog>
  </div>
</template>

<script>
import {
  getadvancedpages,
  getModalityList,
  getDepList,
  postcallregistercancelappointment,
  postcallregistercancelappointmentlist,
  getCheckRoomList,
  getDepAreaList,
  getappointmentresultmodel,
  getBigPartList,
  getHisCheckroomgetSmallpartlist,
  postsigninorder,
  postreportcall,
  getlistResult,
  getCheckGroupList,
  getHospitalAppsettings,
  mobileJwtAccessTokenEncrypt,
  getSysHospitalGetModelByCode
} from '@/api/api.js'
import { setLocalStorage, getLocalStorage, removeLocalStorage } from '@/utils/localStorage'
import enc from '@/utils/aes'
import { debounce, setOrderListCache, getKyReaderCardOptions, setIsRememberSelect, getIsRememberSelect, getOrderListCache, isNullMore, isNull, deleteOrderListCache, timeTransform } from '@/utils/utils' // this.$utils
import aes from '@/utils/aes'
// import { getItemListFunc } from '@/api/common'
import HisRecordDialog from '@/views/appointCenter/hisRecordDialog'
import cameraPhoto from '@/components/appCamera/cameraPhoto'
import virtualselect from '@/components/virtualselect/index'
import paginationCont from '@/components/Pagination/index'
import WSCardReader from '@/components/WSCardReaderNew/index'
import rtUtil from '@/components/WSCardReaderNew/readerType'
import { operateTypeFlr, dateFormatter } from '@/utils/validate'
import InfoDialog from './infoDialog'
import applyImageDialog from './applyImageDialog'
import EditAppoDialog from './editAppoDialog'
import LogDialog from './logDialog'
import MessageDialog from './messageLog'
import PrintAppo from './printAppo'
import PatBasicInfo from './patBasicInfo'
import SendMessage from './sendMessage'
import { Options } from '@/utils/constant'
// import { getDateYMD } from '@/utils/utils'
import tableStyle from '@/utils/tableStyle.js'
import SetIndexDialog from './setIndexDialog'
import SignUpDialog from './signUpDialog'
// import applyFunction from '@/mixin/applyFunction'
import bus from '@/api/bus'
import { mapGetters } from 'vuex'
import XLSX from 'xlsx'
import { saveAs } from 'file-saver'
const CHECK_APPLY_FILE_KEY = 'CHECK_APPLY_FILE'
const CHECK_FORM_DEFAULT_KEY = 'CHECK_FORM_DEFAULT'
let DEFAULTSEARCHDATS = 7
let DEFAULTSEARCHSBODYDATS = 90
let registerRoom = '' // getLocalStorage('UserPermision') || ''
let keysArr = Options.sourceEnquirySelectKey
let string = '' // getLocalStorage('localSetMemory') || `{"modalitytype":"","depArea":"","areaName":"","dep":"","deps":[]}`
let localSetMemoryObj = '' // JSON.parse(string)
export default {
  name: '',
  components: {
    paginationCont, InfoDialog, EditAppoDialog, LogDialog, MessageDialog,
    PrintAppo, PatBasicInfo, WSCardReader, virtualselect, cameraPhoto, applyImageDialog, SetIndexDialog, SendMessage, SignUpDialog, HisRecordDialog
  },
  filters: {
    operateTypeFlr
  },
  data() {
    return {
      wardNoDisabled: false,
      isShowWardNo2: false,
      isShowHisDialog: false,
      isShowSetIndexDialog: false,
      isShowSignUpDialog: false,
      isShowLogDialog: false,
      isShowInfoDialog: false,
      isOpenCamera: false,
      isShowResult: false,
      patBasicInfoVisible: false,
      proptype: '',
      hisTypeOptions: [],
      appointSourceFlag: window.g.appointSourceFlag,
      appointSourceNameList: window.g.appointSourceNameList,
      isSaveOperateWidth: window.g.isSaveOperateWidth,
      isCheckedNoCancel: window.g.isCheckedNoCancel,
      SOURCEINDEX_TODAY: false,
      // SOURCEINDEX_TODAY: false,
      isSelectChange: false,
      isRememberSelect: false,
      checkGroupOptions: [],
      tableColumn: [],
      applyImageList: [], // 纸质申请单图片列表
      wsType: '',
      isAccurate: false,
      applyInfoHospital: window.g.applyInfoHospital || '',
      // tijianTotijianhao: window.g.tijianTotijianhao,
      newVersionReaderHospital: window.g.newVersionReaderHospital || [],
      isInsertTransportType: window.g.isInsertTransportType,
      kyCardReaderOptions: '',
      isPrintReport: window.g.isPrintReport,
      // tableFixed: { fixed: 'left' },
      isExtend: 0,
      showAll: true,
      // isApplyListOrderFront: window.g.isApplyListOrderFront, // 黄石专用检查时间，访问号，检查技师提前
      isMpiOrPid: window.g.isMpiOrPid,
      // isFilterMerge: window.g.isFilterMerge,
      selectedLeft: [],
      selectedRight: [],
      leftOptionsShort: [
        { value: 0, label: '检查部门', field: 'scheduledDep', selected: '请选择检查部门', optionsWidth: '180', disabled: false },
        { value: 1, label: '预约来源', field: 'appointmentType', selected: '请选择预约来源', optionsWidth: '180', disabled: false },
        { value: 2, label: '患者类型', field: 'PatientType', selected: '请选择患者类型', optionsWidth: '180', disabled: false }
      ],
      leftOptions: [
        { value: 0, label: '检查部门', field: 'scheduledDep', selected: '请选择检查部门', optionsWidth: '180', disabled: false },
        { value: 1, label: '预约来源', field: 'appointmentType', selected: '请选择预约来源', optionsWidth: '180', disabled: false },
        { value: 2, label: '患者类型', field: 'PatientType', selected: '请选择患者类型', optionsWidth: '180', disabled: false },
        { value: 3, label: '影像区域', field: 'depArea', selected: '请选择影像区域', optionsWidth: '180', disabled: false },
        { value: 4, label: '检查设备', field: 'scheduledModality', selected: '请选择检查设备', optionsWidth: '180', disabled: false },
        { value: 5, label: '检查分组', field: 'checkGroup', selected: '请选择检查分组', optionsWidth: '180', disabled: false },
        { value: 6, label: '检查机房', field: 'callRoom', selected: '请选择检查机房', optionsWidth: '180', disabled: false },
        { value: 7, label: '预约机房', field: 'scheduledRoom', selected: '请选择预约机房', optionsWidth: '180', disabled: false },
        { value: 8, label: '检查状态', field: 'checkStatus', selected: '请选择检查状态', optionsWidth: '180', disabled: false },
        { value: 9, label: '打印状态', field: 'numberPrintStatus', selected: '请选择打印状态', optionsWidth: '180', disabled: false },
        { value: 10, label: '检查部位', field: 'dengjipart', selected: '请选择检查部位', optionsWidth: '180', disabled: false },
        { value: 11, label: '检查项目', field: 'checkpos', selected: '请选择检查项目', optionsWidth: '180', disabled: false },
        { value: 12, label: '优先级别', field: 'grade', selected: '请选择优先级别', optionsWidth: '180', disabled: false },
        { value: 13, label: '收费状态', field: 'chargeStatus', selected: '请选择收费状态', optionsWidth: '180', disabled: false },
        { value: 14, label: '床旁标志', field: 'bedside', selected: '请选择床旁标志', optionsWidth: '180', disabled: false },
        { value: 15, label: '检查班次', field: 'medcine', selected: '请选择检查班次', optionsWidth: '180', disabled: false },
        { value: 16, label: '申请科室', field: 'applyDepartment', selected: '请选择申请科室', optionsWidth: '180', disabled: false }
      ],
      groupOptions: {
        depArea: [],
        medcine: [],
        applyDepartment: [],
        scheduledDep: [],
        scheduledModality: [],
        scheduledRoom: [],
        callRoom: [],
        checkStatus: Options.appointmentCheckStatusOptions,
        appointmentType: [],
        PatientType: Options.patientTypeItemOptions.map(item => item.label),
        numberPrintStatus: ['已打印', '未打印'],
        bedside: ['床旁', '非床旁'],
        dengjipart: [],
        checkpos: [],
        checkGroup: [],
        grade: [],
        chargeStatus: ['未收费', '已收费']
      },
      isGetLISResult: this.$store.state.user.appSetting.isGetLISResult,
      rightPlaceholders: [],
      rightGroupWidth: [],
      recordSelect: [],
      // isaddColumn: window.g.IS_ADD_NEWCOLUMN,
      dateOptions: [
        { value: 1, label: '开单时间' },
        { value: 2, label: '登记时间' },
        { value: 3, label: '预约时间' },
        { value: 4, label: '打印时间' },
        { value: 5, label: '检查时间' },
        { value: 6, label: '报告时间' },
        { value: 7, label: '审核时间' }
      ],
      dateValue: '预约时间',
      dateCommonValue: '',
      tableStyle: tableStyle,
      rules: {
        scheduledDttm: { required: true, message: '请选择预约日期', trigger: 'change' }
      },
      // departmentOptions: [],
      // emergencySignsOptions: Options.emergencyOptionsMap,
      gradeOptions: [],
      applyDepartmentOptions: [],
      // transportTypeOptions: [],
      scheduledRoomOptions: [],
      // transportToolsOptions: [],
      // inpatientWardOptions: [], // 病区
      chargeStatusOptions: ['未收费', '已收费'],
      isDisabled: false,
      hospitalCode: this.$store.state.user.hospitalCode,
      hospitalName: this.$store.state.user.hospitalName,
      formData: {
        ApplyHospitalCode: '',
        hospitalCode: this.$store.state.user.hospitalCode,
        applyDepartment: '',
        depArea: [],
        scheduledDep: [],
        scheduledModality: [],
        callRoom: [],
        scheduledRoom: [],
        checkStatus: '',
        appointmentType: [],
        wardNo: '',
        patientName: '',
        registerDoctor: '',
        accessionNo: '',
        scheduledDttm: '',
        StartDate: '',
        hisType: '',
        EndDate: '',
        Xno: '', // 检查号
        DeleteStatus: !window.g.isNotCheckedDelete, // 是否排除已删除状态：0否;1是;
        PatientType: [], // 患者类型：住院、门诊、体检、绿检、急诊、外院
        numberPrintStatus: '', // 打印状态
        bedside: '', // 床旁标志
        dateType: 3, // 查询日期类型：1开单日期、2登记日期、3预约日期、4打印日期、5检查日期、6报告日期、7审核日期 默认3
        dengjipart: [],
        checkpos: [],
        medcine: '',
        grade: [], // 优先级别
        chargeStatus: '', // 收费状态
        transportType: '', // 运送方式
        transportTools: '', // 转运工具
        sqdep: '', // 申请科室
        checkGroup: [] // 检查分组
        // DateSelectType: 0 // 日期查询条件：0等于、1大于、2大于等于、3小于、4小于等于
      },
      signNo: '',
      signAccessNo: [],
      // medcineOptions: [],
      searchOptions: ['PID', '卡号', '访问号', '影像号', '发票号', '门诊号', '住院号', '病人ID', '身份证号', '申请单号', '登记人', '手机号'],
      printType: ['已打印', '未打印'],
      bedsideOptions: ['床旁', '非床旁'],
      searchValue: '卡号',
      searchCommonValue: '',
      depAreaOptions: [],
      scheduledModalityOptions: [],
      scheduledDepOptions: [],
      callRoomOptions: [],
      dateSelectTypeOptions: ['等于', '大于', '大于等于', '小于', '小于等于'],
      patientTypeOptions: Options.patientTypeItemOptions.map(item => item.label),
      checkStatusOptions: Options.appointmentCheckStatusOptions,
      // appointmentTypeOptions: [],
      loading: false,
      tableData: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      delTips: [
        '',
        '至少选择一个病人',
        '只能选择一个或相同患者批量取消',
        '已签到申请单不能取消',
        '只能选择一个或相同患者批量取消,且所选患者的记录中已签到申请单不能取消'
      ],
      multipleSelection: [],
      // isEnableBatchprint: window.g.IS_ENABLE_BATCHPRINT,
      // isEnableBatchrebook: !window.g.IS_ENABLE_BATCHREBOOK,
      timeRange: [],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime())
            end.setTime(end.getTime())
            // // console.log('start, end', start, end)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '一天',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            end.setTime(end.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '三天',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 180)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近十二个月',
          onClick(picker) {
            let end = new Date()
            let start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 360)
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 360)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      appoint_type: window.g.APPOINT_TYPE || '前台登记',
      dialogVisibleLog: false, // 日志
      dialogMessageLog: false, // 短信日志
      logId: '',
      logHospitalCode: '',
      dialogVisibleEditAppo: false, // 修改，改约
      isEditInfo: false,
      fromCheckDepartment: false,
      appoInfo: {},
      dialogVisibleDetail: false, // 详情弹框
      applyImageDialogVisible: false, // 纸质申请单图片预览窗口
      appoDetail: {},
      applyFiles: {}, // 申请单附件
      dengjipartOptions: [], // 大部位
      checkposOptions: [], // 小部位
      sortName: 'CallRegisterKey',
      sortOrder: '', // 温附二要默认asc
      referralInfos: [],
      pubcliKey: '',
      titleChange: '改约',
      patTypeColor: {}
    }
  },
  watch: {
    // dialogVisibleEditAppo(val) {
    //   if (val) {
    //     console.error(val)
    //   }
    // }
  },
  computed: {
    ...mapGetters(['wardNoOptions', 'rowCurr', 'hisActivedIndex', 'gradeList', 'appointmentTypeOptions', 'departmentOptions', 'medcineOptions', 'transportTypeOptions', 'transportToolsOptions']),
    hisActivedIndex() {
      let hisActivedIndex = this.$store.state.patient.hisActivedIndex
      // if (hisActivedIndex == 3) {
      //   delete this.tableFixed.fixed
      // }
      return hisActivedIndex
    },
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    reportPrintTime() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.reportPrintTime || 0
    },
    isStyleUpdate() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isStyleUpdate || false
    },
    isFilterMerge() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isFilterMerge || window.g.isFilterMerge
    },
    patSourceOptions() {
      let patientSourceOptions = (this.appConfig.checkPatTypeTable || Options.patientTypeItemOptions).concat([{ label: '全部', value: 0 }])
      let psArr = []
      patientSourceOptions.forEach(item => {
        item.name = item.label || item.name
        delete item.label
        psArr.push(item)
      })
      // let arr = this.operatorPatSourceOption(psArr)
      return psArr
    },
    isShowHisType() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isShowHisType || false
    },
    patTypeLink() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.patTypeLink || false
    },
    canPrintStatus() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.canPrintStatus || ['已审核']
    },
    stestIDMergeOutID() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.stestIDMergeOutID || false
    },
    saveByPic() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.saveByPic || false
    },
    isShowApplyCheck() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isShowApplyCheck) || window.g.IS_APPLYCHECK_PICKHIS
    },
    isRequiredItems() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isRequiredItems
    },
    // 已预约列表下拉菜单可调节
    showMenuSort() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.showMenuSort || []
    },
    tijianTotijianhao() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.tijianTotijianhao) || window.g.tijianTotijianhao
    },
    // tijianShow() {
    //   return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.tijianShow) || window.g.tijianShow
    // },
    paramConfig() {
      return this.$store.state.settings.paramConfig
    },
    emergencyOptionsMapFromDB() {
      let map = {
        '': ''
      }
      if (this.appConfig.checkHisTable && Array.isArray(this.appConfig.checkHisTable) && this.appConfig.checkHisTable.length) {
        this.appConfig.checkHisTable.forEach(item => {
          if (item) {
            map[item.value] = item.name || item.label
          }
        })
      } else {
        map = Options.emergencyOptionsMap
      }
      // // console.log('emergencyOptionsMapFromDB', map)
      return map
    },
    isSelectMoreCheckStatus() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isSelectMoreCheckStatus
    },
    patTypeToAppointed() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.patTypeToAppointed
    },
    isAddAuthInEdit() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isAddAuthInEdit
    },
    isShowApplyDepart() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isShowApplyDepart
    },
    isSortInfo() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isSortInfo
    },
    isGetHisDeps() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isGetHisDeps
    },
    isChooseDeps() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isChooseDeps
    },
    isLineThrough() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isLineThrough
    },
    sourceIndexToday() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.SOURCEINDEX_TODAY) || window.g.SOURCEINDEX_TODAY
    },
    exportToExcel() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.exportToExcel
    },
    // SOURCEINDEX_TODAY() {
    //   return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.SOURCEINDEX_TODAY) || window.g.SOURCEINDEX_TODAY
    // },
    DEFAULTSEARCHDATS() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.DEFAULTSEARCHDATS || DEFAULTSEARCHDATS
    },
    isOpenDefSechSomebodyDays() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isOpenDefSechSomebodyDays
    },
    defSechSomebodyDays() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.defSechSomebodyDays || DEFAULTSEARCHSBODYDATS
    },
    // 附件是否显示
    applyCheckFileSHow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.applyCheckFileSHow
    },
    isShowRememberSelectBtn() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isShowRememberSelectBtn
    },
    isShowWardNo() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.isShowWardNo
    },
    KYCARDREADER_OPTIONS() {
      let arr = ((this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.kyReaderCardNameArr && this.appConfig.baseConfig.kyReaderCardNameArr.length) && this.appConfig.baseConfig.kyReaderCardNameArr) || []
      console.log('KYCARDREADER_OPTIONS=>arr', arr)
      let options = getKyReaderCardOptions(arr)
      console.log('KYCARDREADER_OPTIONS=>options==预约页面', options)
      return (options.length && options) || window.g.KYCARDREADER_OPTIONS || window.g.KYCARDREADER_OPTIONS_FUDING
    },
    showDelBtn() {
      let flag = 0
      if (this.multipleSelection.length === 0) {
        flag = 1
      } else {
        flag = 0
        // let isCheck = false
        this.multipleSelection.forEach(it => {
          if (it.patientId != this.multipleSelection[0].patientId) {
            flag = 2
          }
          // if (it.checkStatus == '签到') {
          //   isCheck = true
          // }
        })
      }
      return flag
    },
    duplicates() {
      return this.selectedLeft.reduce((obj, item, index) => {
        obj[item] = obj[item] || []
        obj[item].push(index)
        return obj
      }, {})
    },
    tableOperateWidth() {
      let width = 380
      if (!this.isMpiOrPid && !this.isPrintReport && !this.isSaveOperateWidth) {
        width = 260
      } else if (!this.isMpiOrPid && this.isPrintReport) {
        width = 380
      } else if (this.isMpiOrPid && this.isPrintReport) {
        width = 200
      } else if (this.isMpiOrPid && !this.isPrintReport) {
        width = 200
      } else if (this.isSaveOperateWidth) {
        width = this.getColumnWidth()
      }
      return width
    }
  },
  created() {
    // registerRoom = getLocalStorage('UserPermision') || ''
    string = getLocalStorage('localSetMemory') || `{"modalitytype":"","depArea":"","areaName":"","dep":"","deps":[]}`
    localSetMemoryObj = JSON.parse(string)
    registerRoom = getLocalStorage('UserPermision') || ''
    string = getLocalStorage('localSetMemory', this.formData.hospitalCode) || `{"modalitytype":"","depArea":"","areaName":"","dep":"","deps":[]}`
    localSetMemoryObj = JSON.parse(string)
    if (localSetMemoryObj.inpatientWard) {
      this.isShowWardNo2 = true
      this.formData.wardNo = localSetMemoryObj.inpatientWard
      this.wardNoDisabled = true
    }
    console.log('this.appConfig', this.appConfig)
    this.isMpiOrPid = this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.mpi || window.g.isMpiOrPid
    this.isRememberSelect = getIsRememberSelect()
    if (this.isRememberSelect && this.isShowRememberSelectBtn) {
      if (!isNull(getOrderListCache())) {
        this.formData = Object.assign(this.formData, getOrderListCache())
        console.log('this.formData=>', this.formData)
      }
    }
    // 增加病区查询
    if (this.isShowWardNo || localSetMemoryObj.inpatientWard) {
      this.leftOptions.push({ value: 13, label: '病区', field: 'wardNo', selected: '请选择病区', optionsWidth: '180', disabled: false })
    }
    // 关于不同医院读卡器配置的动态获取
    this.kyCardReaderOptions = this.KYCARDREADER_OPTIONS || window.g.KYCARDREADER_OPTIONS || window.g.KYCARDREADER_OPTIONS_FUDING || rtUtil.defaultType
    // let lsSearchValue = getLocalStorage('yjyy-searchValue', this.formData.hospitalCode)
    let lsSearchValue = this.searchOptions.indexOf(getLocalStorage('yjyy-searchValue', this.formData.hospitalCode)) > -1 ? getLocalStorage('yjyy-searchValue', this.formData.hospitalCode) : ''
    if (lsSearchValue) {
      this.searchValue = lsSearchValue
    } else {
      if (window.g.defaultSearchValue) {
        this.searchValue = window.g.defaultSearchValue
      } else {
        this.searchValue = '卡号'
      }
    }
    this.$getHospitalList()
    const fileObj = getLocalStorage(CHECK_APPLY_FILE_KEY, this.formData.hospitalCode)
    if (fileObj) {
      this.applyFiles = JSON.parse(fileObj)
    }
    const checkFormDefault = getLocalStorage(CHECK_FORM_DEFAULT_KEY, this.formData.hospitalCode)
    if (checkFormDefault) {
      const cfd = JSON.parse(checkFormDefault)
      this.appoint_type = cfd.appoint_type || window.g.APPOINT_TYPE || '前台登记'
    }
    // 判断连接中是否有预约日期，若有则使用连接上的
    let query = this.$route.query
    let appoint_date = decodeURIComponent(query.appoint_date) || ''
    if (!isNull(appoint_date)) {
      this.timeRange = [appoint_date.substring(0, 10), appoint_date.substring(0, 10)]
    } else {
      console.log('到这里1')
      this.initTimeRange()
    }
    this.isExtend = 0
    if (!this.isShowRememberSelectBtn) {
      deleteOrderListCache()
    }
    // 用于存放设置当中的配置判断
    this.setDefaultConfig()
    this.isRememberSelect = false
  },
  mounted() {
    // let abc = [1, 2, 3]
    // abc.splice(1, 1)
    // console.log('abc', abc)
    console.log('%7C', decodeURIComponent('%7C'))
    this.fromCheckDepartment = !(this.appointSourceFlag && (this.appointSourceNameList || ['自助预约', '移动预约']).includes('检查科室') && (!this.$hasPermission(['YJYY10008098']))) && this.appointmentTypeOptions && this.appointmentTypeOptions.filter(item => item === '检查科室').length > 0
    // 温州市中心医院
    // this.searchOptions = (this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') ? ['影像号', '住院号', '访问号', '身份证号', 'PID', '卡号', '门诊号', '申请单号', '登记人', '病人ID'] : this.searchOptions
    this.searchValue = (this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') ? '影像号' : this.searchValue
    this.searchOptions = this.showMenuSort.length > 0 ? this.showMenuSort : this.searchOptions
    if (this.stestIDMergeOutID) {
      console.log('到这里', this.searchOptions)
      this.searchOptions.forEach((item, index) => {
        if (item == '门诊号' || item == '体检号') {
          this.searchOptions[index] = '门诊/体检号'
          console.log('this.searchValue', this.searchValue)
        }
      })
    }
    this.sortName = this.isSortInfo && localStorage.getItem('sortDefault') ? localStorage.getItem('sortDefault') : 'CallRegisterKey'
    let query = this.$route.query
    // let testArr = 'kU4JHpVc+a2Lz76iMc4Bvg=='
    // console.log('query', query, encodeURIComponent(testArr))
    if (!isNull(query)) {
      let accessionNo = query.accessionNo || query.accessno // 'kU4JHpVc+a2Lz76iMc4Bvg=='
      let appoint_date = decodeURIComponent(query.appoint_date) || ''
      console.log('accessionNo-init', accessionNo)
      console.log('2024-10-14', encodeURIComponent('2024-10-14'))
      if (accessionNo) {
        if (accessionNo && accessionNo.indexOf('%3D') > -1) {
          try {
            accessionNo = aes.AESDecrypt(decodeURIComponent(accessionNo))
          } catch (e) {
            this.$message.warning('访问号解密失败')
          }
        } else if (accessionNo && accessionNo.indexOf('==') > -1) {
          console.log('=====')
          try {
            accessionNo = aes.AESDecrypt(accessionNo)
            console.log('accessionNo==', accessionNo)
          } catch (e) {
            this.$message.warning('访问号解密失败')
          }
        }
        if (appoint_date && appoint_date.indexOf('%3D') > -1) {
          try {
            appoint_date = aes.AESDecrypt(decodeURIComponent(appoint_date))
          } catch (e) {
            this.$message.warning('访问号解密失败')
          }
        } else if (appoint_date && appoint_date.indexOf('==') > -1) {
          console.log('=====')
          try {
            appoint_date = aes.AESDecrypt(appoint_date)
            console.log('appoint_date==', appoint_date)
          } catch (e) {
            this.$message.warning('访问号解密失败')
          }
        }
        console.log('accessionNo', accessionNo)
        this.searchValue = '访问号'
        this.searchCommonValue = accessionNo
        if (this.searchCommonValue) {
          if (!isNull(appoint_date)) {
            this.timeRange = [appoint_date.substring(0, 10), appoint_date.substring(0, 10)]
          } else {
            console.log('到这里2')
            this.initTimeRange()
          }
          this.search()
        }
      } else {
        const tokenInfo = JSON.parse(localStorage.getItem('JJYY_SET_TOKENINFO'))
        if (tokenInfo.accessionNo) {
          accessionNo = tokenInfo.accessionNo
          this.searchValue = '访问号'
          this.searchCommonValue = accessionNo
          if (this.searchCommonValue) {
            this.initTimeRange()
            this.search()
          }
        }
      }
    }
    (this.isShowWardNo || localSetMemoryObj.inpatientWard) && this.getInpatientWard()
    // if (this.hisActivedIndex == 3) {
    //   delete this.tableFixed.fixed// 这行代码非常重要，不要删除了哦，不然在检查预约登记页面的已预约列表中会有BUG,会出现操作栏为空白的现象
    // }
    this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
    try {
      this.getScheduledDepOptions() // 获取检查部门
      this.getTypeOptions() // 获取预约来源
      if (this.isShowApplyDepart || this.isFilterMerge) {
        this.getDepartment()
      }
      // this.isGetHisDeps && this.isChooseDeps && JSON.parse(getLocalStorage(CHECK_FORM_DEFAULT_KEY, this.formData.hospitalCode)) ? this.formData.scheduledDep = JSON.parse(getLocalStorage(CHECK_FORM_DEFAULT_KEY, this.formData.hospitalCode)).deps || [] : this.formData.scheduledDep
      this.isGetHisDeps && this.isChooseDeps && JSON.parse(getLocalStorage(CHECK_FORM_DEFAULT_KEY, this.formData.hospitalCode)) ? this.formData.scheduledDep = JSON.parse(getLocalStorage(CHECK_FORM_DEFAULT_KEY, this.formData.hospitalCode)).deps || [] : this.formData.scheduledDep
      // this.tijianShow && this.searchOptions.indexOf('体检号') === -1 ? this.searchOptions.push('体检号') : null
    } catch (err) {
      // console.log(err)
    }
    this.isFilterMerge ? this.getLocalStorageInfo() : null
    // bus.$on('notFromRouter', (data) => {
    //   if (data) {
    //     this.timeRange = this.SOURCEINDEX_TODAY ? [dateFormatter(new Date(new Date().getTime()), false), dateFormatter(new Date(new Date().getTime()), false)] : [dateFormatter(new Date(new Date().getTime() - 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false), dateFormatter(new Date(new Date().getTime() + 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false)]
    //   }
    // })
    bus.$off('selectedRowCurr')
    bus.$on('selectedRowCurr', (data) => {
      // console.log('selectedRowCurr->data', data)
      this.$nextTick(() => {
        if (!isNull(getOrderListCache())) {
          this.formData = Object.assign(this.formData, getOrderListCache())
          console.log('this.formData=>', this.formData)
        } else {
          // this.timeRange = this.SOURCEINDEX_TODAY ? [dateFormatter(new Date(new Date().getTime()), false), dateFormatter(new Date(new Date().getTime()), false)] : [dateFormatter(new Date(new Date().getTime() - 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false), dateFormatter(new Date(new Date().getTime() + 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false)]
        }
        // 左右联动情况下，根据PID等查询的时候，自动清除已预约列表的选择框里的指
        if (this.searchCommonValue) {
          keysArr && keysArr.forEach(item => {
            if (!isNullMore(this.formData[item])) {
              if (item != 'hospitalCode') {
                this.formData[item] = ''
              }
            }
          })
        }
        if (isNull(data)) {
          // 判断连接中是否有预约日期，若有则使用连接上的
          let query = this.$route.query
          let appoint_date = decodeURIComponent(query.appoint_date) || ''
          console.log('appoint_date', appoint_date)
          if (!isNull(appoint_date)) {
            this.timeRange = [appoint_date.substring(0, 10), appoint_date.substring(0, 10)]
          } else {
            console.log('到这里4')
            this.initTimeRange()
          }
          this.search()
        } else {
          if (this.patTypeLink) {
            let ps = []
            const patientType = this.patSourceOptions.filter(item => item.value == data.patientSource)[0].name
            console.log('patientType', patientType)
            ps.push(patientType)
            this.formData.PatientType = (patientType == '全部' || data.patientSource == 0) ? [] : ps
            console.log('this.formData.PatientType', this.formData.PatientType)
            // this.formData.patientSource = ps
          }
          this.changeList(data)
        }
      })
    })
    // 创建键盘模拟输入的事件监听
    this.$refs.WSCardReader.addInputEventListener('formQueryTextIptInSourceEnquiry', () => {
      return this.searchCommonValue.trim()
    })
    // // 获取社保卡、医保凭证 用户信息 searchValue searchCommonValue
    // bus.$off('WSCardReader_msg_sourceEnquiryIndex')
    // bus.$on('WSCardReader_msg_sourceEnquiryIndex', (res) => {
    //   this.searchValue = res.searchWay
    //   this.searchCommonValue = res.searchText
    //   // this.search()
    //   this.$nextTick(() => {
    //     this.search()
    //   }, 200)
    // })
    // // 监听键盘事件
    // document.getElementById('formQueryTextIptInSourceEnquiry').addEventListener('keydown', (event) => {
    //   // // console.log(`按下的keyCode:${event.keyCode}, 按下的key:${event.key}`)
    //   // 根据不同的键执行不同的操作
    //   if (event.keyCode == 13 || event.key == 'Enter') {
    //     let qText = this.searchCommonValue.trim()
    //     console.warn('qText', qText)
    //     if (qText == '*=-*' || qText.length == 28 || qText.substr(0, 4).toUpperCase() == 'FEQR' || qText.indexOf(':') > -1) {
    //       // 市民卡先刷出的是*=-*
    //       this.$refs.WSCardReader.wsChange('', qText)
    //     }
    //   }
    // })
    this.$nextTick(() => {
      this.setTableCol()
    }, 200)
    // this.gethospitalInfo(this.formData.hospitalCode)
    // console.log('this.formData.depArea', this.formData.depArea)
  },
  methods: {
    toSearch() {
      this.initTimeRange()
      this.search()
    },
    close(comp) {
      if (comp == 'PatBasicInfo') {
        this.patBasicInfoVisible = false
      }
    },
    gethospitalInfo(hospitalCode) {
      console.log('gethospitalInfo')
      return new Promise(async resolve => {
        // 如果publick不存在在去请求，不然就不请求了
        if (!this.pubcliKey) {
          await getSysHospitalGetModelByCode({ hospitalCode }).then(res => {
            console.log('gethospitalInfo=>res', res)
            this.pubcliKey = res.content.guomiKey
          })
        }
        resolve()
      })
    },
    getToken(patientId) {
      // console.log('getToken', this.pubcliKey)
      return new Promise(async resolve => {
        await this.gethospitalInfo(this.formData.hospitalCode)
        const userInfo = this.$store.state.user.userInfo
        const data = {
          isRefreshToken: false,
          organizationCode: userInfo.hospitalCode,
          queryValue: patientId,
          operateUser: userInfo.userName,
          OperateCode: userInfo.userCode
        }
        const encData = enc.SM2Encrypt(JSON.stringify(data), this.pubcliKey)
        const params = {
          organizationCode: userInfo.hospitalCode,
          data: '04' + encData
        }
        let t = ''
        mobileJwtAccessTokenEncrypt(params).then(res => {
          if (res && res.code === 10000) {
            t = res.content.accessToken
            resolve(t)
          } else {
            alert('网络异常，请求接口出错')
            resolve('')
          }
        })
      })
    },
    async openPrintReport(index, row) {
      const sirenToken = await this.getToken(row.patientId)
      let str = window.g.API_ROOT || ''
      if (window.g.API_ROOT.lastIndexOf('\/') == window.g.API_ROOT.length - 1) {
        str = window.g.API_ROOT.substring(0, window.g.API_ROOT.length - 1)
      }
      const pdfUrl = str + '/api/v1/callregister/readreportpdf?AccessToken=' + sirenToken.replace('Bearer ', '') + '&HospitalCode=' + this.formData.hospitalCode + '&AccessNo=' + row.accessionNo
      const h = window.innerHeight - 80
      window.openDoors = window.open(pdfUrl, '_blank', 'width=1120,height=' + h + ',left=400,top=20')
      try {
        window.openDoors.window.onload = function () {
          setTimeout(function () {
            window.openDoors.window.print()
          }, 1000)
        }
      } catch (e) {
        console.error('存在跨域无法自动打开打印')
      }
    },
    // 刷卡返回结果的处理
    getWSCardReaderMsg(res) {
      if (res.searchText) {
        this.searchValue = res.searchWay
        this.searchCommonValue = res.searchText
        this.$nextTick(() => {
          this.search()
        }, 200)
      } else {
        this.searchCommonValue = ''
      }
    },
    closeDialog() {
      this.isShowEditAppoDialog = false
    },
    signIn() {
      this.isShowSignUpDialog = true
      this.$nextTick(() => {
        this.$refs.signIn.signUpVisible = true
      })
    },
    getSignInfo(params) {
      // console.error('params', params)
      // 重置入参
      this.resetParam()
      this.signNo = params.signNo
      this.formData.StartDate = params.StartDate
      this.formData.EndDate = params.EndDate
      this.timeRange = [this.formData.StartDate, this.formData.EndDate]
      this.formData.scheduledDep = params.scheduledDep
      this.formData.checkStatus = params.checkStatus
      this.fetchData()
      // this.$refs.signIn.signUpVisible = false
      // console.error('this.signAccessNo', this.signAccessNo)
    },
    setDefaultConfig() {
      if (this.patTypeToAppointed) {
        let configInfo = JSON.parse(this.paramConfig.hospitalParameterContent)
        configInfo.checkPatTypeTable.forEach(element => {
          if (element.colorStatus) {
            this.patTypeColor[element.name] = {
              color: element.fontColor,
              value: element.value
            }
            console.error('this.patTypeColor', this.patTypeColor)
            document.body.style.setProperty('--color' + element.value, element.fontColor)
          }
        })
      }
    },
    searchValueReset() {
      (this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') ? this.searchValue = '影像号' : null
      this.$store.commit('patient/setFilterPatientInfo', [])
    },
    bedSidePrint() {
      this.loading = true
      const userInfo = this.$store.state.user.userInfo
      let params = []
      if (this.multipleSelection.length <= 20) {
        if (this.referralInfos.length > 0 && this.applyInfoHospital == 'wzszxyy') {
          params = JSON.parse(JSON.stringify(this.referralInfos))
        } else {
          this.multipleSelection.forEach(item => {
            params.push({
              type: 'printAppoint',
              ...item,
              appointType: this.appoint_type,
              operateCode: userInfo.userCode,
              operateUser: userInfo.userName
            })
          })
        }
        params['IsMergePrint'] = 1
        this.$refs.PrintAppo && this.$refs.PrintAppo.print(params)
      } else {
        this.loading = false
        this.$message.warning('批量打印不超过20条!')
      }
    },
    judgeTrueOrFalse(prop) {
      if (prop == 'triggerDttm' || prop == 'checkStatus' || prop == 'bedno' || prop == 'bedNo' || prop == 'scheduledDttm' || prop == 'callId') {
        return true
      }
      return false
    },
    // exportToExcelBtn() {
    //   // 获取表格的DOM元素
    //   const elTable = this.$refs.table
    //   const wb = XLSX.utils.table_to_book(elTable.$el)
    //   // console.log('wb', wb)
    //   const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    //   try {
    //     // 导出Excel表格
    //     saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '已预约列表.xlsx')
    //   } catch (e) {
    //     if (typeof console !== 'undefined') console.error(e, wbout)
    //   }
    //   return wbout
    // },
    includeValue(list, v) {
      let resultIndex = list.findIndex(item => item.p == v)
      if (resultIndex > -1) {
        return true
      }
      return false
    },
    includeValueAndReturnText(list, v) {
      let obj = {
        patientName: '患者姓名',
        patientSex: '患者性别',
        scheduledDep: '检查部门',
        checkpos: '检查项目',
        accessionNo: '访问号',
        hospitalCode: '医院代码',
        applyHospitalCode: '预约医院代码',
        hospitalName: '医院名称',
        applyHospitalName: '预约医院',
        patientType: '患者类型',
        scheduledModality: '检查设备',
        checkStatus: '检查状态',
        beginTime: '开始时间',
        endTime: '结束时间',
        patientBirthDate: '出生日期'
      }
      let resultIndex = list.findIndex(item => item.p == v)
      if (resultIndex > -1) {
        return {
          b: true,
          text: list[resultIndex].n
        }
      }
      // key != 'patientNameSex' && key != 'checkExamPart' && key != 'patientName' && key != 'patientSex' && key != 'scheduledDep' && key != 'checkpos')
      if (v == 'patientBirthDate' || v == 'hospitalName' || v == 'endTime' || v == 'beginTime' || v == 'checkStatus' || v == 'scheduledModality' || v == 'patientType' || v == 'applyHospitalName' || v == 'applyHospitalCode' || v == 'hospitalCode' || v == 'accessionNo' || v == 'patientName' || v == 'patientSex' || v == 'scheduledDep' || v == 'checkpos' || v == 'checkGroup') {
        return {
          b: true,
          text: obj[v]
        }
      }
      return {
        b: false
      }
    },
    getHospitalSetting() {
      getHospitalAppsettings({ hospitalCode: this.formData.hospitalCode }).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.isGetLISResult = res.content.isGetLISResult
        }
      }).catch(() => {
        this.loading = false
      })
    },
    exportToExcelBtn() {
      // console.log('tableColumn', this.tableColumn)
      this.tableColumn.forEach(item => {
        // console.log('item.p', item.p)
      })
      // 获取表格的DOM元素
      // 为数据创建工作表
      const worksheet = XLSX.utils.json_to_sheet(this.tableData)
      // console.log('worksheet', worksheet)
      // 设置身份证号格式为文本
      const range = XLSX.utils.decode_range(worksheet['!ref'])
      // console.log('range', range)
      let result = {}
      for (let row = range.s.r; row <= range.e.r; row++) {
        for (let col = range.s.c; col <= range.e.c; col++) {
          const cellRef = XLSX.utils.encode_cell({ c: col, r: row })
          // console.log('worksheet[cellRef].t', worksheet[cellRef].t)
          if (worksheet[cellRef] && worksheet[cellRef].t == 's' && worksheet[cellRef].v && !this.includeValue(this.tableColumn, worksheet[cellRef].v)) {
            // 把值的格式都转化为常规格式即可解决数字长度太长，而变成科学技术法格式的问题。
            // console.log('worksheet[cellRef]', worksheet[cellRef])
            // delete worksheet[cellRef]
          }
          // console.log('col, row', col, row)
          // console.log('cellRef', cellRef)
          if (worksheet[cellRef] && worksheet[cellRef].v) {
            result = this.includeValueAndReturnText(this.tableColumn, worksheet[cellRef].v)
            if (result.b) {
              worksheet[cellRef].v = result.text
            }
          }
          if (worksheet[cellRef] && worksheet[cellRef].v && !this.includeValue(this.tableColumn, worksheet[cellRef].v)) {
            // 把值的格式都转化为常规格式即可解决数字长度太长，而变成科学技术法格式的问题。
            worksheet[cellRef].t = 'general'
          }
        }
      }

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new()
      // workbook.Sheets.Sheet1.map(item => {
      //   if (item.A1.t == 's') {
      //     if (item.A1.v == 'telephone') {
      //       item.A1.v = '手机号'
      //     }
      //   }
      //   return item
      // })
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
      // 生成Excel文件
      const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })

      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      }

      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), '已预约列表.xlsx')
    },
    getDynamicClass(row) {
      // 你的条件逻辑可以在这里组织
      let styleAdd = ''
      let styleColor = ''
      // console.error('row', row.grade == '急诊')
      if (this.isLineThrough && row.chargeStatus === '未收费' && row.patientType != '住院') {
        styleAdd = styleAdd + 'text-underline'
      }
      if ((this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') && (row.checkType === '阳性' || row.hiv === '阳性' || row.hcv === '阳性' || row.lisSerumGastric === '阳性' || row.creatinine === '阳性' || row.rpr === '阳性')) {
        styleColor = ' text-yellow'
      }
      if ((this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') && (row.patientType === '急诊' || row.grade == '急诊' || row.grade === 'VIP')) {
        styleColor = ' text-red'
      }
      styleAdd = styleAdd + styleColor
      return styleAdd
    },
    computedClassValue(row) {
      const isTextUnderline = this.isLineThrough && row.patientType !== '住院' && row.chargeStatus === '未收费'
      return isTextUnderline ? 'text-underline' : ''
    },
    getSortType(label) {
      if (label === 'patientNameSex' || label === 'callRoom') {
        return 'custom'
      } else if (['triggerDttm', 'checkDttm', 'checkStatus', 'scheduledDttm'].includes(label)) {
        return true
      } else {
        return false
      }
    },
    sortBys({ column, prop, order }) {
      console.log('排序sortBys=>order', order)
      // 按姓名排序
      let propChange = prop === 'patientNameSex' ? 'patientName' : prop
      this.sortName = propChange.charAt(0).toUpperCase() + propChange.slice(1)
      setLocalStorage('sortDefault', this.sortName, this.formData.hospitalCode)
      // 通用
      if (order != null) {
        this.sortOrder = order === 'ascending' ? 'asc' : (order === 'descending' ? 'desc' : '')
        setLocalStorage('sortOrder', this.sortOrder, this.formData.hospitalCode)
      } else {
        this.sortOrder = ''
        this.sortName = ''
        removeLocalStorage('sortDefault')
      }
      this.fetchData()
    },
    initTimeRange() {
      // 初始化时间
      if (this.searchCommonValue) {
        if (this.sourceIndexToday) { // 已预约列表设置查询日期为一天
          this.timeRange = [dateFormatter(new Date(new Date().getTime()), false), dateFormatter(new Date(new Date().getTime()), false)]
        } else {
          if (this.isOpenDefSechSomebodyDays) {
            this.timeRange = [dateFormatter(new Date(new Date().getTime() - 3600 * 1000 * 24 * this.defSechSomebodyDays), false), dateFormatter(new Date(new Date().getTime() + 3600 * 1000 * 24 * this.defSechSomebodyDays), false)]
          }
        }
      } else {
        if (this.sourceIndexToday) { // 已预约列表设置查询日期为一天
          this.timeRange = [dateFormatter(new Date(new Date().getTime()), false), dateFormatter(new Date(new Date().getTime()), false)]
        } else {
          this.timeRange = [dateFormatter(new Date(new Date().getTime() - 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false), dateFormatter(new Date(new Date().getTime() + 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false)]
        }
      }
    },
    copyText(event) {
      const text = event.target.dataset.text
      const input = document.createElement('input')
      input.value = text
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
    },
    onHeaderDragEnd(newWidth, oldWidth, column, event) {
      if (column.label === '操作' && this.isSaveOperateWidth) {
        setLocalStorage('operatorWidth', newWidth, this.formData.hospitalCode)
      }
    },
    getColumnWidth() {
      return getLocalStorage(`operatorWidth`, this.formData.hospitalCode) ? getLocalStorage(`operatorWidth`, this.formData.hospitalCode) : 260
    },
    handleColumnWidthChange(column, width) {
      const columnIndex = this.$refs.elTable.columns.indexOf(column) // 获取列索引
      console.error('columnIndex', columnIndex)
      // saveColumnWidth(columnIndex, width); // 保存列宽度
    },
    timeRangeChange() {
      this.isSelectChange = true
      // console.log('this.timeRange', this.timeRange)
      this.formData.StartDate = this.timeRange[0]
      this.formData.EndDate = this.timeRange[1]
      // 时间的缓存有问题，要做的话，需要单独做个缓存
      // if (this.isRememberSelect) {
      //   setOrderListCache(this.formData)
      // } else {
      //   let item = {
      //     StartDate: this.timeRange[0],
      //     EndDate: this.timeRange[1]
      //   }
      //   setOrderListCache(item)
      // }
      // let timaRange = {
      //   StartDate: this.timeRange[0],
      //   EndDate: this.timeRange[1]
      // }
      // setOrderListTimeRangeCache(timaRange)
      // const d1 = this.timeRange[0]
      // const d2 = this.timeRange[1]
      // this.timeRange = [getDateYMD(new Date(d1).getTime()), getDateYMD(new Date(d2).getTime())]
      this.search()
    },
    setTableCol() {
      this.configInfo = {}
      if (this.paramConfig) {
        if (this.paramConfig.hospitalParameterContent) {
          this.configInfo = this.paramConfig.hospitalParameterContent
          this.configInfo1 = JSON.parse(this.configInfo)
          if (this.configInfo1.bookTable) {
            this.tableColumn = this.configInfo1.bookTable
          }
        }
        if (this.paramConfig.userParameterContent) {
          this.configInfo = this.paramConfig.userParameterContent
          this.configInfo1 = JSON.parse(this.configInfo)
          if (this.configInfo1.bookTable) {
            this.tableColumn = this.configInfo1.bookTable
          }
        }
      }
      if (!this.tableColumn || Array.isArray(this.tableColumn) && this.tableColumn.length == 0) {
        this.tableColumn = Options.recordColumnsConfig
      }
      // console.log('this.tableColumn', this.tableColumn)
    },
    openSettings() {
      this.isShowSetIndexDialog = true
      this.$nextTick(() => {
        this.$refs.setIndexDialog.dialogVisible = true
      })
    },
    getLocalStorageInfo() {
      this.selectedLeft = this.leftOptions.map(option => option.field)
      // this.formData.scheduledDep = JSON.parse(getLocalStorage('scheduledDep'))
      // console.error('this.formData.scheduledDep', this.formData.scheduledDep)
      const cachedSelectedLeft = !isNull(getLocalStorage('selectedLeft', this.formData.hospitalCode)) && JSON.parse(getLocalStorage('selectedLeft', this.formData.hospitalCode)) || ''
      const cachedRightPlace = !isNull(getLocalStorage('rightPlaceholders', this.formData.hospitalCode)) && JSON.parse(getLocalStorage('rightPlaceholders', this.formData.hospitalCode)) || ''
      const rightGroupWidth = !isNull(getLocalStorage('rightGroupWidth', this.formData.hospitalCode)) && JSON.parse(getLocalStorage('rightGroupWidth', this.formData.hospitalCode)) || ''
      console.log('cachedSelectedLeft', JSON.stringify(cachedSelectedLeft))
      if (cachedSelectedLeft && cachedSelectedLeft.length === this.leftOptions.length) {
        this.selectedLeft = cachedSelectedLeft
        if (getOrderListCache()) {
          const cachedSelectedLeft = !isNull(getLocalStorage('selectedLeft', this.formData.hospitalCode)) && JSON.parse(getLocalStorage('selectedLeft', this.formData.hospitalCode)) || []
          cachedSelectedLeft.forEach((element, index) => {
            console.error('element', element, index)
            this.selectedRight[index] = this.formData[element]
          })
        }
        this.selectedLeft.forEach((element, index) => {
          this.selectedRight[index] = ''
        })
      } else {
        setLocalStorage('selectedLeft', JSON.stringify(this.selectedLeft), this.formData.hospitalCode)
        // setLocalStorage('selectedLeft', JSON.stringify(this.selectedLeft))
      }
      this.recordSelect = [...this.selectedLeft]
      if (cachedRightPlace && cachedRightPlace.length === this.leftOptions.length) {
        this.rightPlaceholders = cachedRightPlace
      } else {
        this.rightPlaceholders = this.leftOptions.map(option => option.selected)
        // setLocalStorage('rightPlaceholders', JSON.stringify(this.rightPlaceholders))
        setLocalStorage('rightPlaceholders', JSON.stringify(this.rightPlaceholders), this.formData.hospitalCode)
      }
      if (rightGroupWidth && rightGroupWidth.length === this.leftOptions.length) {
        this.rightGroupWidth = rightGroupWidth
      } else {
        this.rightGroupWidth = this.leftOptions.map(option => option.optionsWidth)
        setLocalStorage('rightPlaceholders', JSON.stringify(this.rightPlaceholders), this.formData.hospitalCode)
      }
    },
    getBirthDay(value) {
      let str = ''
      let result = ''
      if (value && value.length >= 8) {
        str = value.substring(0, 8)
        result = str.substring(0, 4) + '-' + str.substring(4, 6) + '-' + str.substring(6, 8)
      }
      return result
    },
    async getDepartment() {
      let params = { HospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode, type: '申请科室' }
      await this.$store.dispatch('settings/set_departmentOptions', params)
      const tokenInfoString = localStorage.getItem('JJYY_SET_TOKENINFO')
      if (tokenInfoString && tokenInfoString.indexOf('applyDepartment') > -1) {
        const tokenInfo = JSON.parse(tokenInfoString)
        if (tokenInfo.applyDepartment) {
          this.formData.sqdep = tokenInfo.applyDepartment || ''
        } else {
          this.formData.sqdep = ''
        }
        if (tokenInfo.isCanSwitch == 1 || tokenInfo.isCanSwitch == 'true' || tokenInfo.isCanSwitch == undefined) {
          this.isDisabled = false
        } else {
          this.isDisabled = true
        }
      }
      let selectedPatientInfo = this.$store.state.patient.selectedPatientInfo
      if (!isNull(selectedPatientInfo)) {
        // 若不为空，已预约列表自动筛选
        this.changeList(selectedPatientInfo)
        // setLocalStorage('isRefresh', '')
      } else {
        // this.search()
        if (this.hisActivedIndex == 3) {
          this.setChangeListValue(this.rowCurr)
          // console.log('this.search()=>mounted')
          // this.search()
        }
      }
      this.groupOptions.applyDepartment = this.applyDepartmentOptions = this.departmentOptions
    },
    async getInpatientWard() {
      // 病区
      // let data = {
      //   HospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
      //   type: '申请病区'
      // }
      // getItemListFunc(data).then(res => {
      //   this.wardNoOptions = res.map(_item => _item.item)
      //   this.groupOptions.wardNo = this.wardNoOptions
      // })
      if (!this.wardNoOptions.length) {
        let params = {
          HospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
          type: '申请病区'
        }
        console.log('params', params)
        await this.$store.dispatch('settings/set_wardNoOptions', params)
        this.groupOptions.wardNo = this.wardNoOptions
      }
    },
    // deleteSuccess() {
    //   // // console.log('deleteSuccess')
    //   this.applyimagegetlist()
    // },
    // 摄像头拍照弹框
    openCamera() {
      this.$nextTick(() => {
        this.$refs.cameraDlg.cameraDlgOpen()
      })
    },
    handleApplySave(index, row) {
      this.isOpenCamera = true
      this.appoDetail = row
      this.$nextTick(() => {
        this.openCamera()
      })
    },
    handleApplyPreview(index, row) {
      this.isShowApplyImageDialog = true
      this.applyImageDialogVisible = true
      this.appoDetail = row
      this.$nextTick(() => {
        this.$refs.applyImageDialog.getApplyImageList()
      }, 200)
    },
    paramCheckDttm(time) {
      if (time) {
        const match = time.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/)
        if (match) {
          const year = match[1]
          const month = match[2]
          const day = match[3]
          const hour = match[4]
          const minute = match[5]
          const second = match[6]
          return `${year}-${month}-${day} ${hour}:${minute}:${second}`
        } else {
          return ''
        }
      } else {
        return ''
      }
    },
    // wsChange(data) {
    //   // // // console.log('wsChange', data)
    //   // this.wsType = data.type
    //   // type: 'ybpzsmk',name: '市民卡'; type: 'dzybpz/dzybpz-fj',name: '医保凭证'; type: 'sbjzfds-fj',name: '磁条卡'
    //   // type: ['sbjzykt-fj', 'sbjzykt-fj'],name: '市民卡'
    //   if (data.type === 'dzybpz' || data.type == 'dzybpz-fj' || data.type == 'dzybpz-tz') { // 医保凭证
    //     this.searchValue = '身份证号'
    //   } else if (data.type === 'sbjzfds-fj' || data.type === 'sbjzykt-fj') { // 市民卡、磁条卡
    //     this.searchValue = '卡号'
    //   } else {
    //     this.searchValue = '卡号'
    //   }
    //   this.$refs.formQueryTextIptInSourceEnquiry && this.$refs.formQueryTextIptInSourceEnquiry.focus()
    // },
    searchValueChange(data) {
      // this.searchCommonValue = ''
      (this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') ? setLocalStorage('yjyy-searchValue', '影像号', this.formData.hospitalCode) : setLocalStorage('yjyy-searchValue', data, this.formData.hospitalCode)
      this.$nextTick(() => {
        this.$refs.formQueryTextIptInSourceEnquiry && this.$refs.formQueryTextIptInSourceEnquiry.focus()
      }, 100)
    },
    setChangeListValue(data) {
      // console.log('setChangeListValue=>data', data)
      if (this.applyInfoHospital == 'fuding' && data.patientSource == 3 && this.hisActivedIndex == 3) {
        // 福鼎医院体检的申请单列表需要时时刷新
        // // // console.log('=======================================111')
      } else {
        this.searchValue = (this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') ? '影像号' : 'PID'
        this.searchCommonValue = ''
        let queryWayOptions = Options.queryWayOptions
        if (data.queryWay >= 0 && data.queryText) {
          if (!data.patientName) {
            this.formData.patientName = ''
          }
          // 根据申请单查询的queryWay（数字）来计算出已预约列表的searchValue（中文)
          queryWayOptions.forEach(item => {
            if (item.value == data.queryWay) {
              this.searchValue = item.label
              this.searchCommonValue = data.queryText
            }
          })
        } else {
          if (data.inpatientId || data.outPatientId || data.idCard || data.patientId) { // 点击列表后查询
            if (data.idCard) {
              this.searchValue = '身份证号'
              this.searchCommonValue = data.idCard
            } else if (data.patientId) {
              this.searchValue = 'PID'
              if (this.isMpiOrPid) { // 温附二开启
                this.searchCommonValue = data.mpi
              } else {
                this.searchCommonValue = data.patientId
              }
            } else if (data.inpatientId) {
              this.searchValue = '住院号'
              this.searchCommonValue = data.inpatientId
            } else if (data.outPatientId) {
              this.searchValue = '门诊号'
              this.searchCommonValue = data.outPatientId
            }
          }
          if (isNull(this.searchCommonValue)) {
            if (data.patientName) {
              // console.log('姓名置空4')
              this.formData.patientName = data.patientName
            }
          } else {
            // console.log('姓名置空2')
            this.formData.patientName = ''
          }
        }
      }
    },
    changeList(data) {
      this.setChangeListValue(data)
      if (this.hisActivedIndex == 3) {
        // console.log('this.search()=>changeList', data)
        if (data.queryText || data.patientName || this.searchCommonValue || this.formData.patientName) {
          this.initTimeRange()
          this.search()
        }
      }
    },
    tableRowClassName({ row }) {
      let cls = ''
      if (this.isLineThrough && row.patientType !== '住院' && row.chargeStatus === '未收费') {
        cls += ' text-underline'
      }
      if (this.patTypeColor[row.patientType]) {
        cls += ' ps' + this.patTypeColor[row.patientType].value
      }
      // 温附二内镜特有的样式, 测试环境不上。麻总要说的
      if (!window.g.jsonpRight && row.scheduledDep == '内窥镜' && (this.applyInfoHospital == 'wenfuer' || this.formData.hospitalCode == '47000593033030211A1001')) {
        // 签到过的状态要绿色的
        if (['已申请', '未检查'].indexOf(row.checkStatus) == -1) {
          cls += ' green-row'
        } else if (row.scheduledModality.indexOf('无痛') > -1) {
          cls += ' blue-font'
        } else if (row.scheduledModality.indexOf('磁控') > -1) {
          cls += ' blue-row'
        } else if (row.scheduledModality.indexOf('支气管镜') > -1) {
          cls += ' yellow-row'
        } else if (row.scheduledModality.indexOf('超声内镜') > -1) {
          cls += ' red-row'
        } else if (row.scheduledModality.indexOf('外科肠镜') > -1) {
          cls += ' purple-row'
        } else if (row.scheduledModality.indexOf('ERCP') > -1 && row.registerpart && row.registerpart.indexOf('鼻胆管') > -1) {
          cls += ' lightgreen-row'
        } else {
          cls += ''
        }
      }
      return cls
    },
    changeInput() {
      // 温附二申请单和已预约列表查询的时候，8位非0开头的跳PID，0开头的跳住院号，其他就是卡号，而且遇到小写p开头的且是8位数的，p要自动转化为大写。
      // 温附二住院号有时候是1开头的，当09999999的时候，下一个就是1*******，但99.9%的情况下，住院号都是0开头，所以出现1的情况的时候，就不用管了，让手动切换
      // console.error('this.searchCommonValue', this.searchCommonValue)
      let qText = this.searchCommonValue.trim()
      if (this.isMpiOrPid) {
        if (qText.length == 8 && qText.substr(0, 1).toUpperCase() == 'P') {
          this.searchValue = 'PID' // PID
          this.searchCommonValue = qText.toUpperCase()
        }
        if (qText.length == 8 && (qText.substr(0, 1) == '0')) {
          this.searchValue = '住院号' // 住院号
        }
      }
    },
    search() {
      // this.initTimeRange()
      // console.log('search=>this.isMpiOrPid', this.isMpiOrPid)
      // 先排除是医保凭证、市民卡、住院卡，然后就是门诊卡
      // if (this.applyInfoHospital == 'fuding') {
      // }
      // 温州市中心医院：
      // 市民卡41位，门诊卡17位，电子医保凭证28位
      // 温附二：住院卡8位
      // 福鼎市医院： 市民卡9位 门诊卡33位 医保卡28位
      let qText = (this.searchCommonValue && this.searchCommonValue.trim()) || ''
      if (!isNull(qText) && (Number(qText) === 0 || Number(qText) === 1)) {
        this.$message.warning('未查到病人信息')
        return
      }
      if (qText) {
        this.$refs.WSCardReader.searchJudge(qText, (res) => {
          const qw = res.searchWay
          if (!isNull(qw)) {
            this.searchValue = qw
          }
          this.doSearch()
        }, (res) => {
          const qw = res.searchWay
          if (!isNull(qw)) {
            this.searchValue = qw
          }
        })
        // if (this.applyInfoHospital == 'fuding') {
        //   if (qText == '*=-*') {
        //     // 市民卡先刷出的是*=-*
        //   } else if (qText.length == 28) {
        //     // 电子医保凭证28位
        //   } else if (qText.length == 9) {
        //     // 市民卡9位-福鼎市医院
        //     // console.log('this.doSearch()=>search()=>qText.length == 9')
        //     this.doSearch()
        //   } else if (qText.length == 33) {
        //     // 门诊卡33位,刷出结果10位
        //     this.doCardInit()
        //   } else {
        //     // console.log('this.doSearch()=>search()=>else1')
        //     this.doSearch()
        //   }
        // } else {
        //   if (qText == '*=-*') {
        //     // 市民卡先刷出的是*=-*
        //   } else if (qText.length == 28) {
        //     // 医保凭证刷出的是28位
        //   } else if (qText.length == 117) {
        //     // 健康卡刷出的是117位 A07990CBE30698D1CF7FD97000B05078FCA0BC363754F528E0E172D771D359F7:0:E7B24F8B09C3EB50A98681899395F7D1:3300A0001APPA0015
        //     this.searchValue = '病人ID' // 病人ID
        //   } else if (qText.length == 68 || qText.length == 116) {
        //     // 医院里的就医助手二维码刷出的是68或116位
        //     this.searchValue = '病人ID' // 病人ID
        //   } else if (qText.indexOf(':') > -1) {
        //     // 健康码中有":"
        //     this.searchValue = '卡号' // 卡号
        //   } else {
        //     if (qText.length == 18 && isIdCard(qText)) {
        //       // console.log('进入这里了？')
        //       this.searchValue = '身份证号' // 身份证号
        //     }
        //     this.doSearch()
        //   }
        // }
      } else {
        this.doSearch()
      }
    },
    doCardInit() {
      if (this.kyCardReaderOptions && this.kyCardReaderOptions.length > 0) {
        this.kyCardReaderOptions[1].data.CardId = this.searchCommonValue
        this.$store.dispatch('patient/setCardId', this.searchCommonValue)
        this.$refs.WSCardReader.readerCardOption = this.kyCardReaderOptions
      } else {
        alert('请先在config.js中配置读卡器参数')
      }
      this.$refs.WSCardReader.readerType = 'sbjzfds-fj' // 磁条卡
      this.$refs.WSCardReader.wsInit()
    },
    doSearch() {
      this.currentPage = 1
      // 这里必须做防抖处理
      debounce(() => {
        this.currentPage = 1
        this.fetchData()
      }, 1000)
    },
    changePagenation() {
      // console.log('fetchData()=>changePagenation')
      this.fetchData()
    },
    fetchData() {
      console.log('fetchData')
      if (this.loading) {
        this.$message.warning('上一次查询尚未结束，请稍等片刻')
        return
      }
      this.loading = true
      this.signAccessNo = []
      this.logId = ''
      this.referralInfos = []
      // let callRoomReferrals = []
      // let appointReferrals = []
      // let itemReferrals = []
      // let smallReferrals = []
      let queryText = (this.searchCommonValue && this.searchCommonValue.trim()) || ''
      // 有卡号、PID等的时候，姓名输入框自动清空
      if (queryText) {
        // console.log('姓名置空')
        this.formData.patientName = ''
      }
      let data = {
        ...this.formData,
        accessionNo: this.searchValue === '访问号' ? this.searchCommonValue : '',
        Xno: this.searchValue === '影像号' ? this.searchCommonValue : '',
        registerDoctor: this.searchValue === '登记人' ? this.searchCommonValue : '',
        magcardId: this.searchValue === '卡号' ? this.searchCommonValue : '',
        inpatientId: this.searchValue === '住院号' ? this.searchCommonValue : '',
        outPatientId: this.searchValue === '门诊号' ? this.searchCommonValue : '',
        testPatientId: this.searchValue === '体检号' ? this.searchCommonValue : '',
        ticketId: this.searchValue === '申请单号' ? this.searchCommonValue : '',
        idCard: this.searchValue === '身份证号' ? this.searchCommonValue : '',
        telephone: this.searchValue === '手机号' ? this.searchCommonValue : '',
        patientId: this.searchValue === 'PID' || (this.searchValue == '病人ID') ? this.searchCommonValue : '',
        fphm: this.searchValue === '发票号' ? this.searchCommonValue : '',
        patientName: this.formData.patientName || '',
        isAccurate: this.isAccurate,
        // fphm: this.searchValue === '发票号' ? this.searchCommonValue : '',
        dateType: this.dateOptions.find(option => option.label === this.dateValue).value,
        depArea: (this.formData.depArea && this.formData.depArea.join(',')) || '',
        scheduledDep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || '',
        scheduledModality: (this.formData.scheduledModality && this.formData.scheduledModality.join(',')) || '',
        callRoom: (this.formData.callRoom && this.formData.callRoom.join(',')) || '',
        checkStatus: (this.formData.checkStatus && this.formData.checkStatus.join(',')) || '',
        StartDate: this.timeRange[0],
        EndDate: this.timeRange[1],
        appointmentType: (this.formData.appointmentType && this.formData.appointmentType.join(',')) || '',
        PatientType: (this.formData.PatientType && this.formData.PatientType.join(',')) || '',
        pageSize: this.pageSize, // 页面大小
        pageNumber: this.currentPage, // 页码
        sortOrder: getLocalStorage('sortOrder', this.formData.hospitalCode) != null ? getLocalStorage('sortOrder', this.formData.hospitalCode) : '', // 排序方式
        sortName: getLocalStorage('sortDefault', this.formData.hospitalCode) != null ? getLocalStorage('sortDefault', this.formData.hospitalCode) : 'CallRegisterKey', // 排序字段
        dengjipart: (this.formData.dengjipart && this.formData.dengjipart.join(',')) || '',
        checkpos: (this.formData.checkpos && this.formData.checkpos.join(',')) || '',
        medcine: this.formData.medcine,
        grade: (this.formData.grade && this.formData.grade.join(',')) || '', // 优先级别
        chargeStatus: this.formData.chargeStatus, // 收费状态
        transportTools: this.formData.transportTools, // 转运工具
        scheduledRoom: this.formData.scheduledRoom && this.formData.scheduledRoom.join(','), // 预约机房
        transportType: this.formData.transportType, // 运送方式
        sqdep: this.formData.sqdep, // 申请科室
        checkGroup: this.formData.checkGroup && this.formData.checkGroup.join(',') // 检查分组
      }
      // 体检号与门诊号是否合并或开启了体检患者对应体检号查询
      if (this.stestIDMergeOutID || (this.tijianTotijianhao && this.searchValue === '体检号')) {
        data.outPatientId = (this.searchValue === '门诊号' || this.searchValue === '体检号' || this.searchValue === '门诊/体检号') ? this.searchCommonValue : ''
        data.testPatientId = ''
      }
      // 温附二环境isMpiOrPid = true
      if ((this.searchValue === '住院号' || this.searchValue === '门诊号') && this.isMpiOrPid) {
        // // console.log('================1111')
        data.patientId = this.searchCommonValue
        data.inpatientId = ''
        data.outPatientId = ''
      } else if (this.searchValue === 'PID' && this.isMpiOrPid) {
        // // console.log('================2222')
        data.patientId = ''
        data.mpi = this.searchCommonValue
        // this.$message.warning('PID暂时查询不了，请通过住院号、姓名、身份号、或直接刷医保凭证、市民卡等方式来查询')
      }
      // console.warn('params.inpatientId==>2', data.inpatientId)
      data.DeleteStatus = data.DeleteStatus ? 1 : 0
      if (this.signNo != '') {
        data.signNo = this.signNo
        data.dateType = 3
      }
      console.log('getadvancedpages=>data', data)
      getadvancedpages(data).then(res => {
        // this.loading = false
        if (res && res.code === 10000) {
          this.tableData = res.content.list
          // // console.log('this.tableData', this.tableData)
          let objKeys = []
          if (this.tableData.length > 0) {
            objKeys = Object.keys(this.tableData[0])
          }
          // // console.log('objKeys', objKeys)
          if (this.tableData) {
            this.tableData.forEach((td) => {
              this.signNo != '' ? this.signAccessNo.push(td.accessionNo) : null
              objKeys.forEach(key => {
                if (key != 'patientBirthDate' && key != 'endTime' && key != 'beginTime' && key != 'checkStatus' && key != 'scheduledModality' && key != 'patientType' && key != 'applyHospitalName' && key != 'applyHospitalCode' && key != 'patientName' && key != 'patientSex' && key != 'scheduledDep' && key != 'checkpos' && key != 'hospitalCode' && key != 'hospitalName' && key != 'rpr' && key != 'hiv' && key != 'hcv' && key != 'creatinine' && key != 'lisSerumGastric' && key != 'hbsag' && key != 'appointmentListDmbId') {
                  if (!this.includeValue(this.tableColumn, key)) {
                    delete td[key]
                  }
                }
                if (key == 'srcfile' || key == 'srcList') {
                  delete td[key]
                }
              })
              let obj = this.mx_hospitalList.find((v) => {
                return td.hospitalCode === v.code
              })
              let aobj = this.mx_hospitalList.find((v) => {
                return td.applyHospitalCode === v.code
              })
              td.hospitalName = obj.name
              td.applyHospitalName = aobj.name
              // if ((this.applyInfoHospital === 'wzszxyy' || this.formData.hospitalCode === '47052555733030211A1001') && td.appointmentType == '转诊预约' && ['未检查', '已申请'].includes(td.checkStatus) && td.numberPrintStatus != '已打印') {
              //   this.referralInfos.push(td)
              //   callRoomReferrals.push(td.callRoom)
              //   appointReferrals.push(this.frtTime(td.scheduledDttm))
              //   itemReferrals.push(td.scheduledDep)
              //   smallReferrals.push(td.checkpos)
              //   // itemReferrals = itemReferrals.length > 0 ? itemReferrals + ',' + td.callRoom : itemReferrals
              //   // let callRoomReferrals = ''
              //   // let appointReferrals = ''
              //   // let itemReferrals = ''
              // }
              if (this.applyCheckFileSHow) {
                td.srcfile = this.applyFiles[td.patientId]
                td.srcList = [this.applyFiles[td.patientId]]
              }
            })
          }
          this.totalCount = res.content.totalCount
          // if (this.applyInfoHospital == 'wzszxyy' && this.hisActivedIndex == 3 && this.referralInfos.length > 0 && (this.searchCommonValue || this.formData.patientName)) {
          //   let confirmMsg = '该患者存在转诊预约检查,' + callRoomReferrals.join(',') + '[' + appointReferrals.join(',') + ']预约了肺HRCT(肺高分辨率CT扫描)检查, 请问是否打印号码单?'
          //   this.$confirm(confirmMsg, '提示', {
          //     confirmButtonText: '是',
          //     cancelButtonText: '否',
          //     type: 'warning'
          //   })
          //     .then(() => {
          //       // 触发打印事件
          //       this.batchPrint()
          //     })
          //     .catch(() => {
          //       this.$message({
          //         type: 'info',
          //         message: '已取消打印'
          //       })
          //     })
          // }
          setTimeout(() => {
            this.signNo != '' && this.tableData.length > 0 ? this.$refs.table.toggleAllSelection() : null
            this.signNo = ''
            this.isShowSignUpDialog = false
            // this.$refs.signIn.signUpVisible = false
          }, 500)
        }
      }).finally(() => {
        this.loading = false
        this.isSelectChange = false
      })
    },
    extendBtn() {
      this.isExtend = this.isExtend == 1 ? 0 : 1
      if (this.isExtend == 1) {
        this.getDepAreaOptions()
        this.getCallRoomOptions()
        this.getScheduledModalityOptions()
        this.getBigPartOptions()
        this.getSmallPartOptions()
        this.getCheckGroupList()
        this.getLevel()
        this.getMedcine()
        let leftOplength = this.leftOptions.length
        if (this.isInsertTransportType) {
          const insertLeftOptions = [
            { value: leftOplength + 1, label: '转运工具', field: 'transportTools', selected: '请选择转运工具', optionsWidth: '180', disabled: false },
            { value: leftOplength + 2, label: '运送方式', field: 'transportType', selected: '请选择运送方式', optionsWidth: '180', disabled: false }
          ]
          this.selectedLeft.push('transportTools')
          this.selectedLeft.push('transportType')
          this.rightPlaceholders.push('请选择转运工具')
          this.rightPlaceholders.push('请选择运送方式')
          this.rightGroupWidth.push('180')
          this.rightGroupWidth.push('180')
          leftOplength = leftOplength + 2
          this.leftOptions = [...this.leftOptions, ...insertLeftOptions]
          this.groupOptions['transportTools'] = []
          this.groupOptions['transportType'] = []
          this.getTransportType()
          this.getTransportTools()
        }
        if (this.isShowHisType) {
          const insertLeftOptions = [
            { value: leftOplength + 1, label: 'HIS类型', field: 'hisType', selected: '请选择HIS类型', optionsWidth: '180', disabled: false }
          ]
          this.leftOptions = [...this.leftOptions, ...insertLeftOptions]
          this.groupOptions['hisType'] = []
          this.getHisTypeOptions()
          this.selectedLeft.push('hisType')
          this.rightPlaceholders.push('请选择HIS类型')
          this.rightGroupWidth.push('180')
        }
        setLocalStorage('rightPlaceholders', JSON.stringify(this.rightPlaceholders), this.formData.hospitalCode)
        setLocalStorage('rightGroupWidth', JSON.stringify(this.rightGroupWidth), this.formData.hospitalCode)
        setLocalStorage('selectedLeft', JSON.stringify(this.selectedLeft), this.formData.hospitalCode)
      }
    },
    handleLeftChange(index) {
      // 记录切换前的选中值
      const selectedLeftValue = this.leftOptions.find(option => option.field === this.selectedLeft[index])
      this.selectedLeft.forEach((element, index2) => {
        // 如果formData有值，就要找selectedLeft中等于element的位置，看看他右边的是否一致
        // console.error('this.formData[element]', this.formData[element])
        if (this.formData[element].length > 0 && this.formData[element] != this.selectedRight[index2]) {
          if (Array.isArray(this.formData[element])) {
            this.formData[element] = this.selectedRight[index2] === undefined ? [] : this.selectedRight[index2]
          } else if (typeof this.formData[element] === 'string') {
            this.formData[element] = this.selectedRight[index2] === undefined ? '' : this.selectedRight[index2]
          }
          if (this.formData[element].length === 0 || this.formData[element] == '') {
            const repeatOption = this.leftOptions.find(option => option.field === element).value
            this.leftOptions[repeatOption].disabled = false
          }
        }
      })
      // leftOptions 中的 ${option.field} 不存在于 selectedLeft 中
      this.leftOptions.forEach(option => {
        if (!this.selectedLeft.includes(option.field)) {
          // console.error('this.formData[element]', this.formData[option.field])
          if (Array.isArray(this.formData[option.field])) {
            this.formData[option.field] = []
          } else if (typeof this.formData[option.field] === 'string') {
            this.formData[option.field] = ''
          }
          option.disabled = false
        }
      })
      // 左侧切换的时候右侧下拉菜单的信息也要发生改变
      this.selectedRight[index] = ''
      this.rightPlaceholders[index] = '请选择' + selectedLeftValue.label
      this.rightGroupWidth[index] = this.leftOptions.find(option => option.field === this.selectedLeft[index]).optionsWidth
      this.handleChange(selectedLeftValue.field)
      const cachedSelectedLeft = !isNull(getLocalStorage('selectedLeft', this.formData.hospitalCode)) && JSON.parse(getLocalStorage('selectedLeft', this.formData.hospitalCode)) || {}
      cachedSelectedLeft[index] = selectedLeftValue.field
      setLocalStorage('rightPlaceholders', JSON.stringify(this.rightPlaceholders), this.formData.hospitalCode)
      setLocalStorage('rightGroupWidth', JSON.stringify(this.rightGroupWidth), this.formData.hospitalCode)
      setLocalStorage('selectedLeft', JSON.stringify(cachedSelectedLeft), this.formData.hospitalCode)
    },
    handleRightChange(index, selectedLeft) {
      // 获取到右边的值改到对应的入参当中
      this.formData[selectedLeft] = this.selectedRight[index]
      // 判断现在的左边是什么值
      // 方案一：如果存在重复，以用户选择的左侧菜单为最高优先级，另一个对象里写的值直接传给当前的菜单右边
      // 方案二：如果存在重复且重复的对象有值则把下拉菜单中的某个对象禁用。
      const disableIndex = this.leftOptions.find(option => option.field === selectedLeft).value
      if (this.formData[selectedLeft].length > 0) {
        this.disableOptions = disableIndex
        this.leftOptions[disableIndex].disabled = true
      } else {
        // 如果没有值
        this.leftOptions[disableIndex].disabled = false
      }
      this.handleChange(this.selectedLeft[index])
    },
    getRightOptions(leftField) {
      return this.groupOptions[leftField]
    },
    getBigPartOptions() {
      const params = {
        hospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
        Dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || '',
        Modality: (this.formData.scheduledModality && this.formData.scheduledModality.join(',')) || ''
      }
      return new Promise(resolve => {
        getBigPartList(params).then(res => {
          if (res.code === 10000) {
            const dengjipartOptions = res.content.list
            this.groupOptions.dengjipart = this.dengjipartOptions = dengjipartOptions
          }
          resolve(res)
        })
      })
    },
    getSmallPartOptions() {
      const params = {
        hospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
        Bigpart: this.formData.dengjipart.join(','),
        Dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || ''
      }
      return new Promise(resolve => {
        getHisCheckroomgetSmallpartlist(params).then(res => {
          if (res.code === 10000) {
            const checkposOptions = res.content.list
            this.groupOptions.checkpos = checkposOptions
            let resultCheckPosOption = []
            checkposOptions.forEach(item => {
              let checkPosItem = {}
              checkPosItem.value = item
              checkPosItem.label = item
              resultCheckPosOption.push(checkPosItem)
            })
            this.checkposOptions = resultCheckPosOption
            // // // console.log('this.checkposOptions', this.checkposOptions)
          }
          resolve(res)
        })
      })
    },
    getCheckGroupList() {
      const params = {
        hospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
        Dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || ''
      }
      return new Promise(resolve => {
        getCheckGroupList(params).then(res => {
          if (res.code === 10000) {
            this.groupOptions.checkGroup = this.checkGroupOptions = res.content.list
            // // // console.log('this.checkposOptions', this.checkposOptions)
          }
          resolve(res)
        })
      })
    },
    handleApply(index, row) {
      console.log('handleApply')
      this.isShowInfoDialog = true
      this.appoDetail = row
      this.$nextTick(async () => {
        this.isShowResult = row.idCard && this.isGetLISResult
        row.idCard && this.isGetLISResult ? this.$refs.infoDialog.getlistResults() : null
        getappointmentresultmodel(row.applyHospitalCode, (row.hospitalCode || this.formData.hospitalCode || this.$store.state.user.hospitalCode), row.accessionNo).then(res => {
          if (res && res.code === 10000) {
            let examination = res.content.examination
            let appointmentListDmb = res.content.appointmentListDmb
            let appointmentResultData = res.content.appointmentResultData
            let examNo = appointmentResultData.examNo ? appointmentResultData.examNo : ''
            let hcv = appointmentResultData.hcv === '阳性' ? 'hcv' : ''
            let hiv = appointmentResultData.hiv === '阳性' ? 'hiv' : ''
            let rpr = appointmentResultData.rpr === '阳性' ? 'rpr' : ''
            let hbsag = appointmentResultData.hbsag === '阳性' ? 'hbsag' : ''
            let lisSerumGastric = appointmentResultData.lisSerumGastric === '阳性' ? 'PRG' : ''
            let creatinine = appointmentResultData.creatinine === '阳性' ? 'SCR' : ''
            let positive = [hcv, hiv, rpr, hbsag, lisSerumGastric, creatinine].filter(item => item != '')
            // let invoiceNo = examination.examinations.invoiceNo || ''
            let examinations = res.content.examination.examinations[0]
            let invoiceNo = examinations.invoiceNo
            let wardName = examination.visit.wardName
            let beginTime = appointmentListDmb && appointmentListDmb.beginTime ? appointmentListDmb.beginTime : ''
            let endTime = appointmentListDmb && appointmentListDmb.endTime ? appointmentListDmb.endTime : ''
            let patientPhone = examination.patient && examination.patient.patientPhone ? examination.patient.patientPhone : ''
            // let examinations = res.content.examination.examinations[0]
            let diseasesHistory = examinations.diseasesHistory || '暂无数据'
            let patientId = examination.patient && examination.patient.patientId ? examination.patient.patientId : ''
            let remarkInfo = examinations.remarkInfo
            let bedNo = examination.visit.bedNo ? examination.visit.bedNo : ''
            let feeType = examinations.feeType ? examinations.feeType : ''
            let patientAge = examination.visit.patientAge
            let applyDoctor = examinations.applyDoctor
            let material = examinations.material
            let gastroscopicMedicine = examinations.gastroscopicMedicine
            let applyDateTime = examinations.applyDateTime
            let applyDepartment = examinations.applyDepartment
            // 检查项目
            let examinationsObj = examinations
            let examinationString = []
            let examinationPartString = []
            // let receiveCost = ''
            let cost = 0
            // console.error('res.content.', res.content)
            if (examinationsObj.examItems) {
              // 多个部位拼接
              examinationsObj.examItems.forEach(itemExamination => {
                examinationString.push(itemExamination.examItemName)
                examinationPartString = []
                itemExamination.feeStatus = itemExamination.feeStatus ? '已收费' : '未收费'
                itemExamination.examParts.forEach(itemExamParts => {
                  if (examinationPartString.indexOf(itemExamParts.examPart) == -1) {
                    examinationPartString.push(itemExamParts.examPart)
                  }
                })
                itemExamination.examPartMerge = JSON.parse(JSON.stringify(examinationPartString.join('、')))
              })
            }
            cost = examinationsObj.cost
            if (examinationsObj.orderBillDetails) {
            //   // 收费明细
              examinationsObj.orderBillDetails.forEach(itemOrderBill => {
                itemOrderBill.feeStatus = itemOrderBill.feeStatus ? '已收费' : '未收费'
              })
            }
            // console.error('')
            var orderBill = examinationsObj.orderBillDetails
            let examItemsSend = examinationsObj.examItems
            let examPurpose = examinationsObj.examPurpose
            // let examObj = {
            //   examItemName: examinationString.join('、'),
            //   examPart: examinationPartString.join('、')
            // }

            let privacyLevel = appointmentResultData.privacyLevel
            this.appoDetail = { ...this.appoDetail, wardName, gastroscopicMedicine, material, applyDoctor, applyDateTime, cost, orderBill, bedNo, examItemsSend, examPurpose, diseasesHistory, feeType, patientAge, beginTime, endTime, patientId, examNo, positive, privacyLevel, patientPhone, remarkInfo, invoiceNo, applyDepartment }
            console.warn('this.appoDetail', this.appoDetail)
          }
        })
        // 获取注意事项
        let params = {
          HospitalCode: row.hospitalCode || this.formData.hospitalCode || this.$store.state.user.hospitalCode,
          AccessNo: row.accessionNo
        }
        // getexamnotice(params).then(res => {
        //   // console.log('get_examnotice_res', res)
        // })
        await this.$store.dispatch('user/get_examnotice', params).then(res => {
          // console.log('get_examnotice_res', res)
        })
        this.dialogVisibleDetail = true
        this.dialogVisibleLog = false
        this.dialogMessageLog = false
      }, 200)
    },
    // 修改患者信息
    handleEditPat(index, row) {
      this.patBasicInfoVisible = true
      this.$nextTick(() => {
        this.$refs.patBasicInfo.patBasicInfoVisible = true
        this.$refs.patBasicInfo.loading = true
        console.log('this.$refs.patBasicInfo.formdata', this.$refs.patBasicInfo.formdata)
        getappointmentresultmodel(row.applyHospitalCode, (row.hospitalCode || this.formData.hospitalCode || this.$store.state.user.hospitalCode), row.accessionNo).then(res => {
          console.log('getappointmentresultmodel=>res', res)
          if (res && res.code === 10000) {
            this.$nextTick(() => {
              this.$refs.patBasicInfo.loading = false
              let patBasicInfo = this.$refs.patBasicInfo.formdata
              let _res = res.content.examination
              let appointmentResultData = res.content.appointmentResultData
              let appointmentListDmb = res.content.appointmentListDmb
              patBasicInfo.hospitalName = this.flrStr(row.applyHospitalName)
              patBasicInfo.dep = this.flrStr(appointmentListDmb.dep)
              patBasicInfo.hospitalCode = this.flrStr(this.formData.hospitalCode || this.$store.state.user.hospitalCode)
              patBasicInfo.accessNo = this.flrStr(row.accessionNo)
              patBasicInfo.patName = this.flrStr(_res.patient.patientName)
              patBasicInfo.gender = this.flrStr(_res.patient.gender)
              patBasicInfo.patAge = this.flrStr(_res.visit.patientAge)
              patBasicInfo.patBirthday = this.flrStr(_res.patient.birthDate)
              patBasicInfo.patTelephone = this.flrStr(_res.patient.patientPhone)
              patBasicInfo.wardName = this.flrStr(_res.visit.wardName)
              patBasicInfo.idCard = this.flrStr(_res.patient.idCard)
              patBasicInfo.wardno = this.flrStr(_res.visit.wardNo)
              patBasicInfo.sqdep = this.flrStr(_res.examinations[0].applyDepartment)
              patBasicInfo.sqdepCode = this.flrStr(_res.examinations[0].applyDepartmentCode)
              patBasicInfo.doctor = this.flrStr(_res.examinations[0].applyDoctor)
              patBasicInfo.doctorCode = this.flrStr(_res.examinations[0].applyDoctorCode)
              patBasicInfo.bedno = this.flrStr(_res.visit.bedNo || _res.visit.bedno)
              // 新增
              patBasicInfo.nameEnglish = this.flrStr(appointmentResultData.nameEnglish)
              patBasicInfo.radioDoctor = this.flrStr(appointmentResultData.radioDoctor)
              patBasicInfo.treatmentType = this.flrStr(appointmentResultData.treatmentType)
              patBasicInfo.price = this.flrStr(_res.examinations[0].cost)
              patBasicInfo.exammark = this.flrStr(_res.examinations[0].remarkInfo)
              patBasicInfo.privacyLevel = res.content.appointmentResultData.privacyLevel
              window.g.isSendParam || this.isRequiredItems ? patBasicInfo.clinicdiagnosis = this.flrStr(_res.examinations[0].clinicdiagnosis) : null
              window.g.isSendParam || this.isRequiredItems ? patBasicInfo.diseasesHistory	 = this.flrStr(_res.examinations[0].diseasesHistory) : null
              // 调用修改患者信息的方法实现身份证信息联动
              // this.$refs.patBasicInfo.idCardChange()
              // 刷新用户出生日期
              this.$refs.patBasicInfo.refreshDate(this.flrStr(_res.patient.birthDate))
              this.$refs.patBasicInfo.resetForm(this.flrStr(_res.patient.idCard))
            })
          }
        })
      }, 200)
    },
    handleCheck(index, row) {
      this.$nextTick(() => {
        this.dialogVisibleEditAppo = true
        this.titleChange = '绿检登记'
        // console.log('this', this.$hasPermission(['YJYY10008045']))
        this.$hasPermission(['YJYY10008052']) ? this.isEditInfo = true : this.isEditInfo = false
        this.$nextTick(() => {
          this.$refs.EditAppoDialog && this.$refs.EditAppoDialog.openRow([row], '1')
          // this.$refs.EditAppoDialog && this.$refs.EditAppoDialog.init()
        }, 200)
      })
    },
    flrStr(val) {
      return val === null ? '' : val
    },
    handleSupplementary(index, row) {
      // let filterPatientInfo = this.$store.state.patient.filterPatientInfo
      this.isShowHisDialog = true
      row.nowAppointment = this.appoint_type || '前台登记'
      this.$nextTick(() => {
        this.$refs.HisRecardDialog.isShowFilterTips = false
        this.$refs.HisRecardDialog.open(row)
      }, 200)
    },
    // 改约
    handleEdit(index, row) {
      console.log('handleEdit=>row', row)
      this.$nextTick(() => {
        this.dialogVisibleEditAppo = true
        this.titleChange = '改约'
        // this.loading = true
        console.log('YJYY10008068', this.$hasPermission(['YJYY10008068']))
        const handSendMsg = this.$hasPermission(['YJYY10008068'])
        row.handSendMsg = handSendMsg
        this.$hasPermission(['YJYY10008040']) ? this.isEditInfo = true : this.isEditInfo = false
        console.log('handleEdit=>this.isEditInfo', this.isEditInfo)
        this.$nextTick(() => {
          this.$refs.EditAppoDialog && this.$refs.EditAppoDialog.openRow([row], '2')
        }, 200)
      })
    },
    // 取消预约
    handleCancel(index, row) {
      let contentTip = `患者:<span style="color:blue;font-size:18px;">${row.patientName}</span>,预约日期：<span style="color:red;font-size:18px;">${this.frtTime(row.scheduledDttm)}</span> 是否取消预约？`
      this.$confirm(contentTip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then((e) => {
        // console.log('e', e)
        this.postcallregistercancelappointment(index, row)
      }).catch((catch_e) => {
        // console.log('catch_e', catch_e)
      })
    },
    batchMessage() {
      // console.error('被点击了')
      let accessNos = []
      // let isVIPAll = true
      this.multipleSelection.forEach(item => {
        // console.log('multipleSelection=>item', item)
        accessNos.push(item.accessionNo)
      })
      let sendMessageInfo = this.$refs.sendMessage.formdata
      sendMessageInfo.accessNoList = accessNos
      this.$refs.sendMessage.messageInfoVisible = true
      this.$refs.sendMessage.isShowContextMenu = false
    },
    // 批量打印测试
    batchCancelPrint() {
      window.indexHIHI = 0
      let row = window.multipleSelection1[window.indexHIHI]
      if (this.appConfig.baseConfig && this.appConfig.baseConfig.qutpatientRefundForm && this.appConfig.baseConfig.qutpatientRefundForm === true && ['门诊', '急诊'].indexOf(row.patientType) > -1) {
        let callBack = () => {
          window.indexHIHI++
          this.handleTfDgPrint(window.indexHIHI, '退费单')
        }
        if (this.multipleSelection.length > 1) {
          this.handleTfDgPrint(window.indexHIHI, '退费单', callBack)
        } else {
          this.handleTfDgPrint(window.indexHIHI, '退费单')
        }
      }
    },
    // 批量取消
    batchCancel() {
      let trips = this.multipleSelection.length == 1 ? '取消' : '批量取消'
      let contentTip = '患者: ' + this.multipleSelection[0].patientName + ', 是否' + trips + '预约？'
      window.multipleSelection1 = this.multipleSelection
      this.$confirm(contentTip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const row = this.multipleSelection[0]
        const params = {
          hospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode, // 预约医院代码
          applyHospitalCode: row.applyHospitalCode, // 申请医院代码
          accessNoList: this.multipleSelection.map((it) => it.accessionNo), // 访问号
          appointmentType: this.appoint_type || '', // 预约类型 预约来源：前台登记、临床预约、移动预约、自助预约
          registerRoom: this.isMpiOrPid ? registerRoom : ''
        }
        this.loading = true
        postcallregistercancelappointmentlist(params).then(res => {
          this.loading = false
          if (res && res.code == 10000) {
            this.batchCancelPrint()
            this.$message.success(res.message || '取消预约提交成功！')
            // console.log('fetchData()=>batchCancel')
            this.fetchData()
          }
        })
      }).catch(() => {})
    },
    // 取消封装
    postcallregistercancelappointment(index, row) {
      const params = {
        hospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode, // 预约医院代码
        applyHospitalCode: row.applyHospitalCode, // 申请医院代码
        accessNo: row.accessionNo, // 访问号
        registerRoom: this.isMpiOrPid ? registerRoom : '',
        appointmentType: this.appoint_type || '' // 预约类型 预约来源：前台登记、临床预约、移动预约、自助预约
      }
      this.loading = true
      postcallregistercancelappointment(params).then(res => {
        this.loading = false
        if (res && res.code == 10000) {
          if (this.appConfig.baseConfig && this.appConfig.baseConfig.qutpatientRefundForm && this.appConfig.baseConfig.qutpatientRefundForm === true && ['门诊', '急诊'].indexOf(row.patientType) > -1) {
            // this.getprintmodelbydep(index, row, '退费单', row.patientType)
            this.handlePrint(index, row, '退费单')
          }
          this.$message.success(res.message || '取消预约提交成功！')
        }
        // console.log('fetchData()=>postcallregistercancelappointment')
        this.fetchData()
      })
    },
    // 打印
    handleTfDgPrint(index, state, next) {
      const userInfo = this.$store.state.user.userInfo
      if (index > window.multipleSelection1.length - 1) {
        return false
      }
      const params = {
        ...window.multipleSelection1[index],
        ModalityType: window.multipleSelection1[index].scheduledModality,
        operateCode: userInfo.userCode,
        operateUser: userInfo.userName,
        tuiState: state
      }
      if (index < window.multipleSelection1.length - 1) {
        this.$refs.PrintAppo && this.$refs.PrintAppo.print(Array(params), next)
      } else if (index == window.multipleSelection1.length - 1) {
        this.$refs.PrintAppo && this.$refs.PrintAppo.print(Array(params))
      }
    },
    // 打印号码单
    handlePrint(index, row, state) {
      this.isShowPrintAppo = true
      const userInfo = this.$store.state.user.userInfo
      const params = {
        ...row,
        type: 'printAppoint',
        ModalityType: row.scheduledModality,
        appointType: this.appoint_type,
        operateCode: userInfo.userCode,
        operateUser: userInfo.userName,
        tuiState: state
      }
      this.$nextTick(() => {
        this.$refs.PrintAppo && this.$refs.PrintAppo.print(Array(params))
      })
    },
    // 打印报告单
    handlePrintReport(index, row, state) {
      // 眼视光医院需要判断审核时间，只有审核后的15分钟后才能打印
      // PDY10023X33030211A5121是眼视光医院的代码
      // checkDttm的时间格式20241028121035
      if (this.reportPrintTime) {
        let checkDttm = timeTransform(row.checkDttm)
        console.log('checkDttm', checkDttm)
        let diffTime = ''
        if (!isNull(checkDttm)) {
          console.log('now', new Date().getTime())
          console.log('checkDttm', new Date(checkDttm).getTime())
          diffTime = new Date().getTime() - new Date(checkDttm).getTime()
          console.log('diffTime / 60 / 1000', diffTime / 60 / 1000)
          let diffMm = diffTime / 60 / 1000
          console.log('diffMm', diffMm)
          const diffMmTarget = this.reportPrintTime
          if (diffMm >= diffMmTarget) {
            this.openPrintReport(index, row)
          } else {
            // 提示无法打印
            this.$message.warning(`报告单审核完${diffMmTarget}分钟后才可打印，还需等待${Math.ceil(diffMmTarget - diffMm)}分钟`)
          }
        } else {
          this.openPrintReport(index, row)
        }
      } else {
        this.openPrintReport(index, row)
      }
      // this.openPrintReport(index, row)
      /* const userInfo = this.$store.state.user.userInfo
      const params = {
        ...row,
        type: 'printReport',
        ModalityType: row.scheduledModality,
        operateCode: userInfo.userCode,
        operateUser: userInfo.userName,
        tuiState: state
      }
      this.$nextTick(() => {
        this.$refs.PrintAppo && this.$refs.PrintAppo.print(Array(params))
      })
      */
    },
    // 退费打印
    handleTFPrint(index, row) {
      if (this.appConfig.baseConfig && this.appConfig.baseConfig.qutpatientRefundForm && this.appConfig.baseConfig.qutpatientRefundForm === true) {
        if (['门诊', '急诊'].indexOf(row.patientType) > -1) {
          this.handlePrint(index, row, '退费单')
        } else {
          this.$message.warning('仅支持门诊急诊的退费打印')
        }
      } else {
        this.$message.warning('未开启门诊退费打印的开关')
      }
    },
    handlePrint2(index, row) {
      window.open(window.g.PAT360)
    },
    handleLog(index, row) {
      this.isShowLogDialog = true
      this.logHospitalCode = row.hospitalCode || this.formData.hospitalCode || this.$store.state.user.hospitalCode
      this.logId = row.accessionNo
      this.dialogVisibleLog = true
      this.dialogVisibleDetail = false
      this.dialogMessageLog = false
      this.$nextTick(() => {
        this.$refs.LogDialog.getDetail(this.logId)
      })
    },
    handleMessageLog(index, row) {
      // console.error('handleLog', index, row)
      this.logHospitalCode = row.hospitalCode || this.formData.hospitalCode || this.$store.state.user.hospitalCode
      this.logId = row.accessionNo
      this.dialogVisibleLog = false
      this.dialogMessageLog = true
      this.dialogVisibleDetail = false
      this.$refs.MessageDialog.getMessageLog(this.logId)
    },
    handleRewrite(index, row) {
      // // // console.log('handleRewrite', index, row)
      this.$message.info('未开放功能，待更新~')
    },
    dlgClose() {
      this.dialogVisibleDetail = false
      this.dialogVisibleLog = false
    },

    frtTime(cellValue) {
      // 处理后台时间
      let time = ''
      if (cellValue) {
        cellValue = cellValue.toString()
        if (cellValue.length > 8) {
          time = cellValue.slice(0, 4) + '-' + cellValue.slice(4, 6) + '-' + cellValue.slice(6, 8) + ' ' + cellValue.slice(8, 10) + ':' + cellValue.slice(10, 12)
        } else {
          time = cellValue.slice(0, 4) + '-' + cellValue.slice(4, 6) + '-' + cellValue.slice(6, 8)
        }
      }
      return time
    },
    frtDay(row, column, cellValue, index) {
      // 处理后台时间
      let time = ''
      if (cellValue) {
        cellValue = cellValue.toString()
        time = cellValue.slice(0, 4) + '-' + cellValue.slice(4, 6) + '-' + cellValue.slice(6, 8)
      }
      return time
    },
    frtTime2(row, column, cellValue, index) {
      // 处理后台时间
      let time = ''
      if (cellValue) {
        cellValue = cellValue.toString()
        time = cellValue.slice(0, 4) + '-' + cellValue.slice(4, 6) + '-' + cellValue.slice(6, 8) + ' ' + cellValue.slice(8, 10) + ':' + cellValue.slice(10, 12) + ':' + cellValue.slice(12, 14)
      }
      return time
    },
    frtBETime(row, column, cellValue, index) {
      // console.log('row.beginTime', row.beginTime)
      const bt = row.beginTime ? row.beginTime.substring(0, 5) : ''
      const et = row.endTime ? row.endTime.substring(0, 5) : ''
      return `${bt} ~ ${et}`
    },
    frStatus(val) {
      // 已申请、未检查、已报告、已审核、已删除
      switch (val) {
        case '已申请':
          return 'info'
        case '未检查':
          return ''
        case '未审核':
          return 'warning'
        case '已报告':
        case '已审核':
          return 'success'
        case '已删除':
          return 'danger'
        default:
          return 'info'
      }
    },
    prStatus(val) {
      switch (val) {
        case '已打印':
          return 'success'
        default:
          return 'warning'
      }
    },
    rememberSelectBtn() {
      this.isRememberSelect = !this.isRememberSelect
      setIsRememberSelect(this.isRememberSelect)
      if (this.isRememberSelect) {
        this.rememberToSelectEvent()
      } else {
        deleteOrderListCache()
      }
      window.location.reload()
    },
    rememberToSelectEvent() {
      // console.log('this.isRememberSelect', this.isRememberSelect)
      if (this.isRememberSelect) {
        let data = this.formData
        // delete data.patientName
        setOrderListCache(data)
      }
    },
    resetParam() {
      // 重置
      this.formData = {
        ApplyHospitalCode: '',
        hospitalCode: this.$store.state.user.hospitalCode,
        depArea: [],
        scheduledDep: [],
        scheduledModality: [],
        callRoom: [],
        scheduledRoom: [],
        checkStatus: '',
        appointmentType: [],
        wardNo: '',
        patientName: '',
        registerDoctor: '',
        accessionNo: '',
        scheduledDttm: '',
        StartDate: '',
        EndDate: '',
        Xno: '', // 检查号
        DeleteStatus: !window.g.isNotCheckedDelete, // 是否排除已删除状态：0否;1是;
        PatientType: [], // 患者类型：住院、门诊、体检、绿检、急诊、外院
        numberPrintStatus: '', // 打印状态
        bedside: '', // 床旁标志
        dateType: 3, // 查询日期类型：1开单日期、2登记日期、3预约日期、4打印日期、5检查日期、6报告日期、7审核日期 默认3
        dengjipart: [],
        checkpos: [],
        medcine: '',
        hisType: '',
        grade: [], // 优先级别
        chargeStatus: '', // 收费状态
        transportType: '', // 运送方式
        transportTools: '' // 转运工具
        // DateSelectType: 0 // 日期查询条件：0等于、1大于、2大于等于、3小于、4小于等于
      }
      if (this.isSelectMoreCheckStatus) {
        this.formData.checkStatus = []
      }
      const tokenInfoString = localStorage.getItem('JJYY_SET_TOKENINFO')
      if (tokenInfoString && tokenInfoString.indexOf('applyDepartment') > -1) {
        const tokenInfo = JSON.parse(tokenInfoString)
        if (tokenInfo.applyDepartment) {
          this.formData.sqdep = tokenInfo.applyDepartment || ''
        } else {
          this.formData.sqdep = ''
          this.isDisabled = false
        }
      }
      this.isRememberSelect && setOrderListCache(this.formData)
      this.leftOptions.forEach(element => {
        element.disabled = false
      })
      this.getDepAreaOptions()
      this.getCallRoomOptions()
      this.getScheduledDepOptions()
      this.getScheduledModalityOptions()
      this.getTypeOptions()
      this.getBigPartOptions()
      this.getSmallPartOptions()
      this.searchCommonValue = ''
      this.selectedRight = []
      this.timeRange = this.sourceIndexToday
        ? [dateFormatter(new Date(new Date().getTime()), false), dateFormatter(new Date(new Date().getTime()), false)]
        : [dateFormatter(new Date(new Date().getTime() - 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false), dateFormatter(new Date(new Date().getTime() + 3600 * 1000 * 24 * this.DEFAULTSEARCHDATS), false)]
    //   this.search()
    },
    // 选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 设置禁止选中
    selectableEvent(row, index) {
      if (row.checkStatus !== '已删除') {
        return true
      }
    },
    // 批量打印号码单
    batchPrint() {
      // // // console.log('选中数据', this.multipleSelection)
      this.loading = true
      const userInfo = this.$store.state.user.userInfo
      let params = []
      if (this.multipleSelection.length <= 20) {
        if (this.referralInfos.length > 0 && this.applyInfoHospital == 'wzszxyy') {
          params = JSON.parse(JSON.stringify(this.referralInfos))
        } else {
          this.multipleSelection.forEach(item => {
            params.push({
              type: 'printAppoint',
              ...item,
              appointType: this.appoint_type,
              operateCode: userInfo.userCode,
              operateUser: userInfo.userName
            })
          })
        }
        params['IsMergePrint'] = 0
        // // console.log('选择数据传参', params)
        this.$refs.PrintAppo && this.$refs.PrintAppo.print(params)
      } else {
        this.loading = false
        this.$message.warning('批量打印不超过20条!')
      }
    },
    // 批量打印报告单
    // batchPrintReport() {
    //   this.loading = true
    //   const userInfo = this.$store.state.user.userInfo
    //   let params = []
    //   this.multipleSelection.forEach(item => {
    //     params.push({
    //       type: 'printReport',
    //       ...item,
    //       operateCode: userInfo.userCode,
    //       operateUser: userInfo.userName
    //     })
    //   })
    //   this.$refs.PrintAppo && this.$refs.PrintAppo.print(params)
    //   // this.isFreshPrintNum()
    // },
    // 批量改约
    batchRebook() {
      // this.isShowEditAppoDialog = true
      this.$nextTick(() => {
        this.isEditInfo = false
        let patId = []
        // let isVIPAll = true
        this.multipleSelection.forEach(item => {
          // // console.log('multipleSelection=>item', item)
          patId.push(item.patientId)
        })
        patId = this.unique(patId)
        if (patId.length == 1) {
          // 只有同一患者才可以一起改约
          let params = []
          this.multipleSelection.forEach(item => {
            params.push({
              ...item
            })
          })
          const hospitalNameRow = params.length > 0 ? params[0].hospitalName : ''
          this.titleChange = '改约'
          this.$refs.EditAppoDialog && this.$refs.EditAppoDialog.versionChange('3', hospitalNameRow)
          this.dialogVisibleEditAppo = true
          this.$nextTick(() => {
            this.timeout02 = setTimeout(() => {
              params.type = '3'
              this.$refs.EditAppoDialog && this.$refs.EditAppoDialog.appointmentPostMessage(params)
            }, 2000)
          })
        } else {
          this.$message.warning('只有同一患者id才可以批量改签！')
          return
        }
      })
    },
    batchSign() {
      const signParam = {
        HospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
        appointmentType: this.appoint_type, // 预约类型 预约来源：前台登记、临床预约、移动预约、自助预约
        accessNoList: this.multipleSelection.map((it) => it.accessionNo).join(',') // 访问号
      }
      const idCard = this.multipleSelection.length > 0 ? this.multipleSelection[0].idCard : ''
      if (idCard != '' && this.$store.state.user.appSetting.isGetLISResult) {
        // this.loading = true
        // 调用检验结果接口
        let getlisParam = {
          HospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
          idCard: idCard,
          isPositive: true
        }
        getlistResult(getlisParam).then(res => {
          if (res && res.code == 10000 && res.content.list.length > 0) {
            // console.error('res', res.content.list)
            let checkResult = res.content.list
            let checkContent = ''
            checkResult.forEach((element, index) => {
              // let txtColor = element.testResult === '阳性' || element.hint === '阳性' ? 'red' : 'black'
              // let positive =  ? '阳性'
              if (element.testResult.indexOf('阳性') > -1 || element.hint.indexOf('阳性') > -1) {
                let positive = '阳性'
                checkContent += (checkContent.length > 0 ? '<br>' : '') + `<span>${element.chineSename}:  </span><span style="color:red;">${positive}</span>`
              }
            })
            this.$confirm(checkContent, '提示', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            }).then(() => {
              this.postSignInfo(signParam)
            })
          } else {
            this.postSignInfo(signParam)
          }
        })
      } else {
        this.postSignInfo(signParam)
      }
    },
    postSignInfo(signParam) {
      postsigninorder(signParam).then(res => {
        this.loading = false
        if (res && res.code == 10000) {
          this.$message.success(res.message || '批量签到成功')
          this.resetParam()
          this.fetchData()
        }
      })
    },
    batchCall() {
      const signParam = {
        HospitalCode: this.formData.hospitalCode || this.$store.state.user.hospitalCode,
        appointmentType: this.appoint_type, // 预约类型 预约来源：前台登记、临床预约、移动预约、自助预约
        accessNoList: this.multipleSelection.map((it) => it.accessionNo).join(',') // 访问号
      }
      this.loading = true
      postreportcall(signParam).then(res => {
        this.loading = false
        if (res && res.code == 10000) {
          this.$message.success(res.message || '批量号码单呼叫成功')
          this.fetchData()
        }
      })
    },
    // 去重
    unique(arr) {
      var newArr = []
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    async getTypeOptions() {
      let params = { HospitalCode: this.formData.hospitalCode || this.hospitalCode, type: '预约来源' }
      await this.$store.dispatch('settings/set_appointTypeOptions', params)
      this.groupOptions.appointmentType = this.appointmentTypeOptions
    },
    async getLevel() {
      let params = { HospitalCode: this.formData.hospitalCode || this.hospitalCode, type: '优先级' }
      await this.$store.dispatch('settings/set_gradeList', params)
      let list = this.gradeList
      const gradeOptions = list.map(it => ({ value: it.item, label: it.item }))
      const groupOptionsGrade = list.map(it => it.item)
      this.gradeOptions = gradeOptions
      this.groupOptions.grade = groupOptionsGrade
    },
    async getMedcine() {
      let params = {
        HospitalCode: this.formData.hospitalCode || this.hospitalCode,
        depArea: (this.formData.depArea && this.formData.depArea.join(',')),
        dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || '',
        type: '检查班次'
      }
      await this.$store.dispatch('settings/set_medcineOptions', params)
      this.groupOptions.medcine = this.medcineOptions
    },
    async getTransportType() {
      let params = {
        HospitalCode: this.formData.hospitalCode || this.hospitalCode,
        depArea: (this.formData.depArea && this.formData.depArea.join(',')) || '',
        dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || '',
        type: '运送方式'
      }
      await this.$store.dispatch('settings/set_transportTypeOptions', params)
      let list2 = this.transportTypeOptions.map(it => {
        it.value = it.item
        it.label = it.item
        return it.label
      })
      this.groupOptions.transportType = list2
    },
    async getHisTypeOptions() {
      let params = {
        HospitalCode: this.formData.hospitalCode || this.hospitalCode,
        type: 'HIS类型'
      }
      await this.$store.dispatch('settings/set_hisTypeOptions', params)
      let list2 = this.hisTypeOptions.map(it => {
        it.value = it.item
        it.label = it.item
        return it.label
      })
      this.groupOptions.hisType = list2
    },
    async getTransportTools() {
      let params = {
        HospitalCode: this.formData.hospitalCode || this.hospitalCode,
        depArea: (this.formData.depArea && this.formData.depArea.join(',')) || '',
        dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || '',
        type: '转运工具'
      }
      await this.$store.dispatch('settings/set_transportToolsOptions', params)
      let list2 = this.transportToolsOptions.map(it => {
        it.value = it.item
        it.label = it.item
        return it.label
      })
      this.groupOptions.transportTools = list2
    },
    getDepAreaOptions() {
      /* 影像区域列表 */
      return getDepAreaList({ hospitalCode: this.formData.hospitalCode || this.hospitalCode }).then(res => {
        if (res.code === 10000) {
          this.depAreaOptions = this.groupOptions.depArea = res.content.list
          return res
        }
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode || this.hospitalCode,
        depArea: this.formData.depArea.join(',')
      }
      return getDepList(params).then((res) => {
        if (res.code === 10000) {
          this.scheduledDepOptions = this.groupOptions.scheduledDep = res.content.list
          return res
        }
      })
    },
    getScheduledModalityOptions() {
      /* 检查设备列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode || this.hospitalCode,
        depArea: (this.formData.depArea && this.formData.depArea.join(',')) || '',
        dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || ''
      }
      return getModalityList(params).then((res) => {
        if (res.code === 10000) {
          this.scheduledModalityOptions = res.content.list
          this.groupOptions.scheduledModality = this.scheduledModality = res.content.list
          return res
        }
      })
    },
    getCallRoomOptions() {
      /* 检查机房列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode || this.hospitalCode,
        depArea: this.formData.depArea.join(','),
        dep: (this.formData.scheduledDep && this.formData.scheduledDep.join(',')) || '',
        modality: this.formData.scheduledModality.join(',')
      }
      return getCheckRoomList(params).then((res) => {
        if (res.code === 10000) {
          this.groupOptions.scheduledRoom = this.groupOptions.callRoom = this.scheduledRoom = this.callRoomOptions = res.content.list
          return res
        }
      })
    },
    async handleChange(e, val) {
      console.log('==e==11111', e)
      console.log('==val==', val)
      console.log('mx_hospitalList', this.mx_hospitalList)
      const hList = this.mx_hospitalList.filter(item => item.code == e)
      switch (val) {
        case 'PatientType':
          console.log('this.formData.PatientType', this.formData.PatientType)
          break
        case 'hospital':
          console.log('hList', hList)
          this.hospitalName = hList[0].name
          console.log('this.hospitalName', this.hospitalName)
          this.$store.commit('settings/SET_wardNoOptions', []) // 初始化病区列表
          this.$store.commit('settings/SET_appointTypeOptions', []) // 初始化预约来源列表
          this.$store.commit('settings/SET_depAreaOptions', []) //  // 影像区域
          this.$store.commit('settings/SET_medcineOptions', []) // 检查班次
          this.$store.commit('settings/SET_transportTypeOptions', []) // 运送方式
          this.$store.commit('settings/SET_transportToolsOptions', []) // 运送工具
          this.$store.commit('settings/SET_hisTypeOptions', []) // his类型
          this.$store.commit('settings/SET_departmentOptions', []) // 申请科室
          this.$store.commit('settings/SET_gradeList', []) // 优先级
          this.depAreaOptions = []
          this.scheduledDepOptions = []
          this.scheduledModalityOptions = []
          this.checkGroupOptions = []
          this.callRoomOptions = []
          this.scheduledRoomOptions = []
          // this.formData.hospitalName =
          this.formData.dengjipart = []
          this.formData.depArea = []
          this.formData.hisType = ''
          this.formData.scheduledDep = []
          this.formData.checkGroup = []
          this.formData.scheduledModality = []
          this.formData.callRoom = []
          this.formData.scheduledRoom = []
          this.formData.appointmentType = []
          this.tableData = []
          this.totalCount = 0
          this.isShowResult = false
          // this.formData.dengjipart = ''
          this.formData.checkpos = []
          this.selectedLeft.forEach((element, index) => {
            this.selectedRight[index] = ''
          })
          try {
            await this.getMedcine()
            await this.getInpatientWard()
            await this.getDepAreaOptions()
            await this.getHospitalSetting()
            this.getScheduledDepOptions()
            this.getScheduledModalityOptions()
            this.getCallRoomOptions()
            this.getTypeOptions()
            // console.log('this.search()=>handleChange')
            this.search()
            this.getBigPartOptions()
            this.getSmallPartOptions()
            this.getCheckGroupList()
            this.publickey = ''
          } catch (err) {
            // console.log(err)
          }
          break
        case 'depArea':
          this.scheduledDepOptions = []
          this.scheduledModalityOptions = []
          this.callRoomOptions = []
          this.scheduledRoomOptions = []
          this.formData.scheduledRoom = []
          this.formData.scheduledDep = []
          this.formData.scheduledModality = []
          this.formData.callRoom = []
          this.formData.scheduledRoom = []
          if (this.isFilterMerge) {
            const length = this.selectedLeft.length
            for (let index = 0; index < length; index++) {
              const element = this.selectedLeft[index]
              if (element === 'callRoom' || element === 'scheduledModality' || element === 'scheduledRoom') {
                this.selectedRight[index] = []
              } else if (element === 'grade') {
                this.selectedRight[index] = []
              }
            }
          }
          try {
            await this.getScheduledDepOptions()
            this.getScheduledModalityOptions()
            this.getCallRoomOptions()
          } catch (err) {
            // console.log(err)
          }
          break
        case 'scheduledDep':
          this.scheduledModalityOptions = []
          this.callRoomOptions = []
          this.scheduledRoomOptions = []
          this.formData.scheduledModality = []
          this.formData.callRoom = []
          this.formData.scheduledRoom = []
          this.formData.dengjipart = []
          this.formData.checkpos = []
          this.checkGroupOptions = []
          this.formData.checkGroup = []
          // setLocalStorage('scheduledDep', this.formData.scheduledDep)
          if (this.isFilterMerge) {
            const length = this.selectedLeft.length
            for (let index = 0; index < length; index++) {
              const element = this.selectedLeft[index]
              if (element === 'callRoom' || element === 'scheduledModality' || element === 'dengjipart' || element === 'checkpos' || element === 'scheduledRoom' || element === 'checkGroup') {
                this.selectedRight[index] = []
              } else if (element === 'grade') {
                this.selectedRight[index] = []
              }
            }
          }
          try {
            await Promise.all([
              this.getScheduledDepOptions(),
              this.getScheduledModalityOptions(),
              this.getCallRoomOptions(),
              this.getBigPartOptions(),
              this.getSmallPartOptions(),
              this.getCheckGroupList()
            ])
          } catch (err) {
            // console.log(err)
          }
          break
        case 'scheduledModality':
          this.callRoomOptions = []
          this.scheduledRoomOptions = []
          this.formData.scheduledRoom = this.formData.callRoom = []
          if (this.isFilterMerge) {
            for (let i = 0; i < this.selectedLeft.length; i++) {
              switch (this.selectedLeft[i]) {
                case 'callRoom':
                  this.selectedRight[i] = []
                  break
                case 'dengjipart':
                  this.selectedRight[i] = []
                  break
                case 'checkpos':
                  this.selectedRight[i] = []
                  break
                case 'scheduledRoom':
                  this.selectedRight[i] = []
                  break
                default:
                  break
              }
            }
          }
          try {
            await this.getCallRoomOptions()
          } catch (err) {
            // console.log(err)
          }
          break
        case 'dengjipart':
          this.formData.checkpos = []
          if (this.isFilterMerge) {
            this.selectedLeft.forEach((element, index) => {
              if (element === 'checkpos') {
                this.selectedRight[index] = []
              }
            })
          }
          try {
            this.getSmallPartOptions()
          } catch (err) {
            // console.log(err)
          }
          break
        case 'scheduledRoom':
          break
        default:
          break
      }
      // console.log('==this.formData==', this.formData)
      this.rememberToSelectEvent()
    }
    // tableCellStyle({ row, column, rowIndex, columnIndex }) {
    //   if (row.patientType === '急诊') {
    //     if (columnIndex === 8 && row.checkStatus === '已申请') {
    //       return 'background: #dadada;color:red'
    //     } else if (columnIndex === 8 && row.checkStatus === '已审核') {
    //       return 'background: #67c23a;'
    //     } else {
    //       return 'color:red;'
    //     }
    //   }
    //   if (columnIndex === 8 && row.checkStatus === '已审核') {
    //     return 'background: #67c23a;'
    //   }
    //   if (columnIndex === 8 && row.checkStatus === '已申请') {
    //     return 'background: #dadada;'
    //   }
    // }
  },
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {
    bus.$off('selectedRowCurr')
    bus.$off('WSCardReader_msg_sourceEnquiryIndex')
    this.timeout01 && clearTimeout(this.timeout01)
    this.timeout02 && clearTimeout(this.timeout02)
    // bus.$off('notFromRouter')
    // document.getElementById('formQueryTextIptInSourceEnquiry').removeEventListener('keydown')
  }
}
</script>
<style lang='scss' scoped>
  .ky-container{
    .content-title{
        margin-left:4px;
        margin-bottom: 16px;
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
    }
    .click-button{
        width: 125px;
    }
}
/* .ky-form-inline-sm .el-form-item{
    margin-right: 6px;
} */
.d-flex{
  display: flex;
}
.el-form-item.select-pd5 /deep/.el-form-item__content{
  display: flex;
}
.needCenter .el-form-item__content{
  display: flex !important;
  flex-direction: row;
  align-items: center
}
/* .el-form-item.select-pd5 /deep/.el-input{
  border-top-left-radius: 0px !important;
  border-bottom-left-radius: 0px !important;
} */
.el-form-item.select-pd5 /deep/.borderChangeSelect.el-select,.el-form-item.select-pd5 /deep/.borderChangeSelect .el-input__inner{
  border-top-right-radius: 0px !important;
  border-bottom-right-radius: 0px !important;
}

.el-form-item.select-pd5 /deep/.el-input,.el-form-item.select-pd5 /deep/.changeBorder.el-input__inner{
  border-top-left-radius: 0px !important;
  border-bottom-left-radius: 0px !important;
}
.el-form-item.select-pd5 /deep/.changeBorder.el-input__inner{
  border-left: none !important;
}
.el-form-item.select-pd0 .select-pd1 /deep/ .el-input--suffix .el-input__inner{
  text-align: left;
}
// .btn-cancel.el-button--warning{
//   background: #999;
//   border: 1px solid #999;
// }
.btn-cancel.is-disabled{
  opacity: .65;
}
/* .el-tag.el-tag--success{
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}
.el-tag.el-tag--info {
    background-color: #dadada;
    border-color: #dadada;
    color: white;
} */
.el-table /deep/ td {
  padding: 4px 0px;
}
.el-table /deep/ th {
  padding: 8px 0px;
}
.el-input__inner {
    line-height: 1px !important;
}
.sexIcon{
  width: 18px;
}
.warning-row {
  background: oldlace;
}
.success-row {
  background: #f0f9eb;
}
.el-button--printReport {
  color: #fff;
  background-color: #999;
  border-color: #999;
}
.el-button--printReport:hover {
  background: #ccc;
  border-color: #ccc;
  color: #fff;
}
.table-operation-btn {
  padding:7px;
}

.el-button+.el-button{
  margin-left: 5px !important;
  margin-right: 0px !important;
}
/deep/.el-table.yiji-table .cell{
  white-space: nowrap;
  min-width: 50px;
}
.mergeIcon1,.mergeIcon2 {
  width: 16px;
  height: 16px;
  text-align: center;
  line-height: 15px !important;
  font-size: 10px;
  border:1px solid #40abe2;
  color:#40abe2;
}
.mergeIcon2 {
  border:1px solid #d4237a;
  color:#d4237a;
}
.no-message {
    color: white;
    background-color: #faa9a9;
    border-color: #faa9a9;
}
.choose-message {
  color: white;
  background-color: #f97a7a;
  border-color: #f97a7a;
}
.no-sign {
    color: white;
    background-color: #92dbed;
    border-color: #92dbed;
}
.choose-sign {
  color: white;
  background-color: #00C0EF;
  border-color: #00C0EF;
}
.no-call {
    color: white;
    background-color: #83e2c2;
    border-color: #83e2c2;
}
.choose-call {
  color: white;
  background-color: #32CD99;
  border-color: #32CD99;
}
.text-underline {
  text-decoration: line-through;
}
.text-red {
  color: red !important;
}
.text-yellow {
  color: rgb(255, 140, 45) !important;
}
/deep/ .el-table.yiji-table .ascending .sort-caret.ascending {
  border-bottom-color: #00C0EF !important;
}
/deep/ .el-table.yiji-table .sort-caret.ascending {
  border-bottom-color: white;
  top: -2px;
}
/deep/ .el-table.yiji-table .sort-caret.descending {
  border-top-color: white;
  bottom: 1px;
}
/deep/ .el-table.yiji-table .descending .sort-caret.descending {
  border-top-color: #00C0EF !important;
}
/deep/ .el-table.yiji-table .mgr-column td {
  background: transparent;
}
.el-table.yiji-table /deep/  .blue-row td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #4c97dd !important;
}
.el-table.yiji-table /deep/  .purple-row td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #c291fd !important;
}
.el-table.yiji-table /deep/  .green-row td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #198c04 !important;
}
.el-table.yiji-table /deep/  .red-row  td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #f37356 !important;
}
.el-table.yiji-table /deep/  .lightgreen-row td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #08cfc7 !important;
}
.el-table.yiji-table /deep/  .blue-font td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #1d46ef !important;
}
.el-table.yiji-table /deep/  .yellow-row td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: #f1ac2f !important;
}
.el-table.yiji-table /deep/  .text-underline td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  text-decoration: line-through;
}
.el-table.yiji-table /deep/ tr td:nth-child(2) {
  background: transparent !important;
}
.el-table.yiji-table /deep/ tr td:nth-child(1) {
  background: transparent !important;
}
.el-table.yiji-table /deep/ .ps1 td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: var( --color1) !important;
}
.el-table.yiji-table /deep/ .ps2 td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: var( --color2) !important;
}
.el-table.yiji-table /deep/ .ps3 td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: var( --color3) !important;
}
.el-table.yiji-table /deep/ .ps4 td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: var( --color4) !important;
}
.el-table.yiji-table /deep/ .ps5 td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: var( --color5) !important;
}
.el-table.yiji-table /deep/ .ps6 td:nth-child(n+3) span:not(.el-tag):not(.el-link--inner) {
  color: var( --color6) !important;
}
</style>
